如何获取类的所有属性的列表?
网友回答:
您可以使用反射来执行此操作:
(从我的库中 – 这获取名称和值)
public static Dictionary<string, object> DictionaryFromType(object atype)
{
if (atype == null) return new Dictionary<string, object>();
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (PropertyInfo prp in props)
{
object value = prp.GetValue(atype, new object[]{});
dict.Add(prp.Name, value);
}
return dict;
}
这个东西不适用于带有索引的属性——为此(它变得笨拙):
public static Dictionary<string, object> DictionaryFromType(object atype,
Dictionary<string, object[]> indexers)
{
/* replace GetValue() call above with: */
object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
}
此外,要仅获取公共属性:(请参阅 BindingFlags 枚举上的 MSDN)
/* replace */
PropertyInfo[] props = t.GetProperties();
/* with */
PropertyInfo[] props = t.GetProperties(BindingFlags.Public)
这也适用于匿名类型!
要仅获取名称,请执行以下操作:
public static string[] PropertiesFromType(object atype)
{
if (atype == null) return new string[] {};
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
List<string> propNames = new List<string>();
foreach (PropertyInfo prp in props)
{
propNames.Add(prp.Name);
}
return propNames.ToArray();
}
对于值来说,这几乎是一样的,或者你可以使用:
GetDictionaryFromType().Keys
// or
GetDictionaryFromType().Values
但我想这有点慢。
网友回答:
反射;例如:
obj.GetType().GetProperties();
对于类型:
typeof(Foo).GetProperties();
例如:
class Foo {
public int A {get;set;}
public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
以下反馈…
null
GetValue
GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
网友回答:
public List<string> GetPropertiesNameOfClass(object pObject)
{
List<string> propertyList = new List<string>();
if (pObject != null)
{
foreach (var prop in pObject.GetType().GetProperties())
{
propertyList.Add(prop.Name);
}
}
return propertyList;
}
此函数用于获取类属性列表。
模板简介:该模板名称为【在C#如何获取类的所有属性的列表?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。