繁体   English   中英

如何获取列表中泛型类的属性?

[英]How to get to the properties of a generic class in a list?

我有一个像这样的通用类:

public class StationProperty<T> : StationProperty
   {
      public StationProperty()
      {

      }

      public StationProperty(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; }
   }

注意继承,我将在后面解释,但抽象类如下所示:

 public interface StationProperty
   {

   }

如您所见,没有花哨的东西-也没有显式的属性。

通过这种机制,我可以像这样传递这些项目的列表:

var props = new List<StationProperty>();
props.Add(new StationProperty<bool>(39, true));
props.Add(new StationProperty<int>(41, 1));

到目前为止,一切都很顺利,但是现在我希望能够做到:

Foreach(var prop in props)
{
     //prop.Id
     //prop.Desc
     //and most importantly prop.Value.GetType or prop.GetType
}

而是缺少这些属性:

在此处输入图片说明

如果我将属性手动添加到抽象类中,则可以求解Id和Desc,但是我很可能需要为Value添加一个对象类型,这将首先消除使用泛型的原因。

所以我的问题是,我想做什么? 而且我要去哪里错了。

您是否在寻找如下代码? 您始终可以获取类型,但在使用接口时只能将值读取为“对象”,泛型类还可以获取强类型值并进行设置。 您还可以允许通过接口设置Value,如果不是正确的类型,则抛出异常。

public class StationProperty<T> : StationProperty
{
    public StationProperty()
    {
    }

    public StationProperty(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 StationProperty.Value
    {
        get { return Value; }
    }

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

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

对于IdDesc属性,获取它们的最简单方法是将它们添加到接口中。

或者在您的示例中,最好使用(抽象)类而不是接口,然后将属性放在那里。 使用这种方法,您不必在泛型类中实现它们。

要在循环中获取Value属性,您需要使用反射:

var val = prop.GetType().GetProperty("Value").GetValue(prop);

该语句应该可以解决问题。

尽管,正如@Steve Mitcham在评论中说的那样,如果您描述原始问题,也许有一个更好的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM