簡體   English   中英

c# 反射,如何獲得泛型類型 class 屬性

[英]c# Reflection, how to get generic type class properties

我有一個通用類型List<Shift>在哪里

public class Shift
{
    [DisplayFormat(DataFormatString = "dd-MMM-yyy '(hours)'")]
    public DateTimeOffset Date { get; set; }

    [DisplayFormat(DataFormatString = "hh':'mm")]
    public TimeSpan TimeWorked { get; set; }
}

我正在嘗試使用反射獲取具有屬性的日程安排道具

var props = typeof(List<ShiftDayItem>).GetProperties();
var ShiftProperty = props.Last();

但是ShiftProperty不包含任何屬性,因此我無法訪問 Date 或 TimeWorked。 反射是不知道這些,還是有其他方法可以讓我獲得這些屬性? 謝謝!

我認為您誤解了 c# 中的“屬性”是什么。 您的Shift class 有 2 個屬性:“日期”和“工作時間”。 要獲取有關這兩個屬性的信息,您可以簡單地編寫: typeof(Shift).GetProperties() 您正在調用typeof(List<ShiftDayItem>).GetProperties() ,它將為您提供 List class 的屬性:計數、容量等。這些完全不相關。

我認為您想從Shift屬性中獲取屬性。 為此,您需要從List<T>獲取泛型參數T 為了實現這一點,你可以這樣做

// Gets the generic type T from List<T>, in your case Shift
// Replace 'typeof(List<Shift>)' with your actual list
Type listType = typeof(List<Shift>).GenericTypeArguments[0];

要從Shift類型中獲取所有屬性,您首先需要獲取可以從中獲取屬性的所有屬性。

// Gets all properties from the generic type T
PropertyInfo[] shiftProperties = listType.GetProperties();

現在您擁有所有屬性,您可以獲取屬性

// Gets all Attributes from each property and puts them in one list (SelectMany)
IEnumerable<Attribute> attributes = shiftProperties.SelectMany(prop => prop.GetCustomAttributes());

您從每個屬性中獲取IEnumerable<Attribute> ,這將導致IEnumerable<IEnumerable<Attribute>>這不是我們想要的。 我們使用了SelectMany方法,它接受每個 IEnumerable 並將其展平為一個。 當你把所有東西放在一起時,你會得到這個

// Gets the generic type T from List<T>, in your case Shift
// Replace 'typeof(List<Shift>)' with your actual list
Type listType = typeof(List<Shift>).GenericTypeArguments[0];

// Gets all properties from the generic type T
PropertyInfo[] shiftProperties = listType.GetProperties();

// Gets all Attributes from each property and puts them in one list (SelectMany)
IEnumerable<Attribute> attributes = shiftProperties.SelectMany(prop => prop.GetCustomAttributes());

您需要更多代碼:

Dim shifttprops= ShiftProperty.PropertyType.GetProperties()
For Each prop in shifttprops
   Dim attrs = prop.CustomAttributes
Next

注意使用CustomAttributes而不是Attributes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM