Warm tip: This article is reproduced from serverfault.com, please click

c# Reflection, how to get generic type class properties

发布于 2020-11-29 09:44:27

I have a Generic type 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; }
}

I'm trying to get schedule props with attributes using reflection

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

But ShiftProperty contains no attributes, so I can't access Date or TimeWorked. Is reflection not aware of these or is there another way for me to get those properties? Thanks!

Questioner
Elvis Skensberg
Viewed
0
Eng. M.Hamdy 2020-11-29 18:14:11

You need more code:

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

Note the use of CustomAttributes instead of Attributes