首页 > C# > 在C#如何获取类的所有属性的列表?

在C#如何获取类的所有属性的列表?

上一篇 下一篇

如何获取类的所有属性的列表?

分割线

网友回答:

您可以使用反射来执行此操作:
(从我的库中 – 这获取名称和值)

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));
}

以下反馈…

  • 若要获取静态属性的值,请将第一个参数传递给nullGetValue
  • 要查看非公共属性,请使用(例如)(返回所有公共/私有实例属性)。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#】栏目查找您需要的精美模板。

相关搜索
  • 下载密码 lanrenmb
  • 下载次数 257次
  • 使用软件 Sublime/Dreamweaver/HBuilder
  • 文件格式 编程语言
  • 文件大小 暂无信息
  • 上传时间 03-30
  • 作者 网友投稿
  • 肖像权 人物画像及字体仅供参考
栏目分类 更多 >
热门推荐 更多 >
微信模板 单页式简历模板 微信图片 自适应 微信文章 html5 微信公众平台 响应式 微信素材 企业网站
您可能会喜欢的其他模板