[英]Get List of Properties from a Class T using C# Reflection
I need to get a list of properties from Class T
- GetProperty<Foo>()
. 我需要从类T
获取属性列表 - GetProperty<Foo>()
。 I tried the following code but it fails. 我尝试了以下代码但它失败了。
Sample Class: 样品类:
public class Foo {
public int PropA { get; set; }
public string PropB { get; set; }
}
I tried the following Code: 我尝试了以下代码:
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;
}
I need to get the List of property name 我需要获取属性名称列表
Expected output: GetProperty<Foo>()
预期输出: GetProperty<Foo>()
new List<string>() {
"PropA",
"PropB"
}
I tried lot of stackoverlow reference, but I can't able to get the expected output. 我尝试了很多stackoverlow引用,但我无法获得预期的输出。
Reference: 参考:
Kindly assist me. 请帮助我。
Your binding flags are incorrect. 您的绑定标志不正确。
Since your properties are not static properties but rather instance properties, you need to replace BindingFlags.Static
with BindingFlags.Instance
. 由于您的属性不是静态属性而是实例属性,因此需要将BindingFlags.Static
替换为BindingFlags.Instance
。
propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
This will appropriately look for public, instance, non-static properties on your type. 这将适当地查找您的类型上的公共,实例,非静态属性。 You can also omit the binding flags entirely and get the same results in this case. 您也可以完全省略绑定标志,并在这种情况下获得相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.