使用C#反射从类T获取属性列表
我需要从Class使用C#反射从类T获取属性列表,c#,properties,system.reflection,type-parameter,C#,Properties,System.reflection,Type Parameter,我需要从ClassT-GetProperty()获取属性列表。我尝试了以下代码,但失败了 示例类: public class Foo { public int PropA { get; set; } public string PropB { get; set; } } 我尝试了以下代码: public List<string> GetProperty<T>() where T : class { List<string> prop
T
-GetProperty()
获取属性列表。我尝试了以下代码,但失败了
示例类:
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;
}
public List GetProperty(),其中T:class{
List propList=新列表();
//获取MyClass类型的所有公共静态属性
PropertyInfo[]propertyInfos;
propertyInfos=typeof(T).GetProperties(BindingFlags.Public|
BindingFlags(静态);
//按名称对属性排序
Array.Sort(propertyInfos,
委托(PropertyInfo propertyInfo1,PropertyInfo propertyInfo2){return propertyInfo1.Name.CompareTo(propertyInfo2.Name);};
//写属性名
foreach(PropertyInfo PropertyInfo in propertyInfos中的PropertyInfo){
propList.Add(propertyInfo.Name);
}
返回列表;
}
我需要得到财产名称的清单
预期输出:GetProperty()
新列表(){
“普罗帕”,
“PropB”
}
我尝试了很多stackoverlow引用,但无法获得预期的输出
参考:
请帮助我。您的绑定标志不正确 由于属性不是静态属性,而是实例属性,因此需要将
BindingFlags.static
替换为BindingFlags.instance
propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
这将适当地查找类型上的公共、实例和非静态属性。在本例中,您还可以完全忽略绑定标志,并获得相同的结果
propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);