c# 反射,如何获取泛型类型 class 属性

c# Reflection, how to get generic type class properties

我有一个通用类型 List<Shift> where

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。 反射不知道这些还是我有另一种方法来获得这些属性? 谢谢!

您需要更多代码:

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

注意使用 CustomAttributes 而不是 Attributes

我认为您误解了 c# 中“属性”的含义。 您的 Shift class 有 2 个属性:“Date”和“TimeWorked”。要获取有关这 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());