簡體   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