Storing different types inside a list?

后端 未结 6 956
广开言路
广开言路 2021-02-19 03:34

Related: A list of multiple data types?

I want to know how to store different array types (including system types) inside an array.

The above question covered ho

6条回答
  •  执笔经年
    2021-02-19 03:48

    You also can use the ? option, make a list of the following type:

    public class MyClass
    {
        public string? x {get;set;}
        public double? y {get;set;}
    }
    

    This way you can select if none, one or both can have a value.

    Or if you don't like the HasValue/Value functions:

    public class MyClass
    {
        public enum EType { String, Double };
    
        EType TypeFilled {get; private set }
    
        string _x;
        public string X { get { return _x; }; set { _x = value; TypeFilled = EType.String; }
        double y;
        public double y { get { return _y; }; set { _y = value; TypeFilled = EType.Double; }
    }
    

    This way the typeFilled property decides what is filled. You could add validation to prevent being set twice etc.

提交回复
热议问题