Adding different type of generic objects into generic list

前端 未结 4 1902
星月不相逢
星月不相逢 2020-12-03 22:01

Is it possible to add different type of generic objects to a list?. As below.

public class ValuePair
{        
    public string Name { get; set;}
          


        
4条回答
  •  半阙折子戏
    2020-12-03 22:53

    Not unless you have a non-generic base-type ValuePair with ValuePair : ValuePair (it would work for an interface too), or use List. Actually, though, this works reasonably:

    public abstract class ValuePair
    {
        public string Name { get; set; }
        public object Value
        {
            get { return GetValue(); }
            set { SetValue(value); }
        }
        protected abstract object GetValue();
        protected abstract void SetValue(object value);
    }
    public class ValuePair : ValuePair
    {
        protected override object GetValue() { return Value; }
        protected override void SetValue(object value) { Value = (T)value; }
        public new T Value { get; set; }
    }
    

    提交回复
    热议问题