如何获取类的属性列表?

563 .net c# reflection properties

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

Mar*_*ell 758

反射; 对于一个实例:

obj.GetType().GetProperties();
Run Code Online (Sandbox Code Playgroud)

对于一种类型:

typeof(Foo).GetProperties();
Run Code Online (Sandbox Code Playgroud)

例如:

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));
}
Run Code Online (Sandbox Code Playgroud)

以下反馈......

  • 要获取静态属性的值,请将null第一个参数传递给GetValue
  • 要查看非公共属性,请使用(例如)GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)(返回所有公共/私有实例属性).

  • 为了完整性,还有TypeModel,由TypeDescriptor.GetProperties(...)公开 - 它允许动态运行时属性(反射在编译时固定). (13认同)
  • 建议:展开答案以涵盖受保护/私有/静态/继承的属性. (5认同)

Luc*_*nes 84

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

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;
}
Run Code Online (Sandbox Code Playgroud)

这个东西不适用于带索引的属性 - 为此(它变得笨重):

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[]{});
}
Run Code Online (Sandbox Code Playgroud)

此外,仅获取公共属性:( 有关BindingFlags枚举的信息,请参阅MSDN)

/* replace */
PropertyInfo[] props = t.GetProperties();
/* with */
PropertyInfo[] props = t.GetProperties(BindingFlags.Public)
Run Code Online (Sandbox Code Playgroud)

这也适用于匿名类型!
要获得名称:

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();
}
Run Code Online (Sandbox Code Playgroud)

并且它只是值相同,或者您可以使用:

GetDictionaryFromType().Keys
// or
GetDictionaryFromType().Values
Run Code Online (Sandbox Code Playgroud)

但我觉得这有点慢.

  • 关于公共属性位,根据链接的MSDN文章:"注意您必须指定Instance或Static以及Public或NonPublic,否则将不返回任何成员." 所以示例代码应该是:`t.GetProperties(BindingFlags.Instance | BindingFlags.Public)`或`t.GetProperties(BindingFlags.Static | BindingFlags.Public)` (4认同)

小智 35

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;
}
Run Code Online (Sandbox Code Playgroud)

此函数用于获取类属性列表.

  • 但这仍然**使用**反射. (8认同)
  • 您可能希望将其更改为使用`yield return`.这不是什么大问题,但它是一种更好的方式. (7认同)
  • 我想这是更好的pObject.GetType().GetProperties().选择(p => p.Name) (2认同)

Jac*_*nkr 23

基于@ MarcGravell的回答,这是一个适用于Unity C#的版本.

ObjectsClass foo = this;
foreach(var prop in foo.GetType().GetProperties()) {
    Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null));
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*jap 22

你可以使用mehod System.Reflection命名空间Type.GetProperties():

PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
Run Code Online (Sandbox Code Playgroud)


Ch *_*man 16

以下代码将为您提供类属性/属性/表列的列表

var Properties = typeof(className).GetProperties().Select(x=>x.Name).ToList();
Run Code Online (Sandbox Code Playgroud)


小智 8

那是我的解决方案

public class MyObject
{
    public string value1 { get; set; }
    public string value2 { get; set; }

    public PropertyInfo[] GetProperties()
    {
        try
        {
            return this.GetType().GetProperties();
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    public PropertyInfo GetByParameterName(string ParameterName)
    {
        try
        {
            return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName);
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue)
    {
        try
        {
            obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue);
            return obj;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

尝试这个:

var model = new MyObject();
foreach (var property in model.GetType().GetProperties())
{
    var descricao = property;
    var type = property.PropertyType.Name;
}
Run Code Online (Sandbox Code Playgroud)

  • 这以最直接的方式回答了OP提出的问题。6行就完成了。 (2认同)

Daa*_*aan 6

你可以使用反射.

Type typeOfMyObject = myObject.GetType();
PropertyInfo[] properties =typeOfMyObject.GetProperties();
Run Code Online (Sandbox Code Playgroud)