C# 如何在列表中设置泛型对象的属性?

C# 如何在列表中设置泛型对象的属性?,c#,generics,C#,Generics,我的班级结构如下所示: public interface IStationProperty { int Id { get; set; } string Desc { get; set; } object Value { get; } Type ValueType { get; } } [Serializable] public class StationProp<T> : IStationProperty

我的班级结构如下所示:

 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"));
公共接口IStationProperty
{
int Id{get;set;}
字符串Desc{get;set;}
对象值{get;}
类型ValueType{get;}
}
[可序列化]
公共类StationProp:IStationProperty
{
公共站点prop()
{
}
public StationProp(int-id,T-val,string-desc=“”)
{
Id=Id;
Desc=Desc;
值=val;
}
公共int Id{get;set;}
公共字符串Desc{get;set;}
公共T值{get;set;}
对象IStationProperty.Value
{
获取{返回值;}
}
公共类型ValueType
{
获取{return typeof(T);}
}
}
这允许我将多个泛型类型添加到同一列表中,如下所示:

 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"));
var props=new List();
道具。添加(新站道具(50,-1,“废话”);
道具。添加(新站道具(53,真,“废话”);
道具。添加(新站道具(54,10,“废话”);
我现在想做的是,在不更改类型的情况下,只更改列表中某个项目的值


这可能吗?

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

(props[0] as StationProp<int>).Value = 5;
(道具[0]作为站道具)。值=5;
如果你不确定它的类型

var item = props[i] as StationProp<int>;
if (item != null)
{
    item.Value = 5;
}
var item=props[i]作为StationProp;
如果(项!=null)
{
项目价值=5;
}

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

不需要投;值是接口的一部分。他只需要给它一个二传手。@Gigi是的,但这涉及到拳击。