如何在列表中设置通用对象的 属性?

How to set a property of a generic object in a list?

我的 class 结构如下所示:

 public interface IStationProperty
   {
      int Id { get; set; }
      string Desc { get; set; }
      object Value { get;  }
      Type ValueType { get; }
   }

   [Serializable]
   public class StationProp<T> : IStationProperty
   {
      public StationProp()
      {
      }

      public StationProp(int id, T val, string desc = "")
      {
         Id = id;
         Desc = desc;
         Value = val;
      }

      public int Id { get; set; }
      public string Desc { get; set; }
      public T Value { get; set; }

      object IStationProperty.Value
      {
         get { return Value; }
      }

      public Type ValueType
      {
         get { return typeof(T); }
      }
   }

这允许我将多个泛型类型添加到同一个列表中,如下所示:

var props = new List<IStationProperty>();
 props.Add(new StationProp<int>(50, -1, "Blah"));
 props.Add(new StationProp<bool>(53, true, "Blah"));
 props.Add(new StationProp<int>(54, 10, "Blah"));

我现在想做的是能够只更改此列表中的项目的值,而不更改类型。

这可能吗?

我假设您知道要更改的项目的索引并且知道它是什么类型。然后就是下面这样

(props[0] as StationProp<int>).Value = 5;

如果您不确定它的类型

var item = props[i] as StationProp<int>;
if (item != null)
{
    item.Value = 5;
}

这是否回答了您的问题?我不太确定你还想达到什么目标。