2
我需要获得类别为T
- GetProperty<Foo>()
的属性列表。我尝试了下面的代码,但它失败了。使用C#反射获取T类属性的列表
样品等级:
public class Foo {
public int PropA { get; set; }
public string PropB { get; set; }
}
我尝试下面的代码:
public List<string> GetProperty<T>() where T : class {
List<string> propList = new List<string>();
// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(T).GetProperties(BindingFlags.Public |
BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos,
delegate (PropertyInfo propertyInfo1,PropertyInfo propertyInfo2) { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
// write property names
foreach (PropertyInfo propertyInfo in propertyInfos) {
propList.Add(propertyInfo.Name);
}
return propList;
}
我需要的属性名称的列表
预期输出:GetProperty<Foo>()
new List<string>() {
"PropA",
"PropB"
}
我尝试了很多stackoverlow参考,但我无法获得预期的输出。
参考:
请帮助我。