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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/737151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:12:39  来源:igfitidea点击:

How to get the list of properties of a class?

c#.netreflectionproperties

提问by

How do I get a list of all the properties of a class?

如何获得一个类的所有属性的列表?

回答by Marc Gravell

Reflection; for an instance:

反射; 例如:

obj.GetType().GetProperties();

for a type:

对于一种类型:

typeof(Foo).GetProperties();

for example:

例如:

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


Following feedback...

关注反馈...

  • To get the value of static properties, pass nullas the first argument to GetValue
  • To look at non-public properties, use (for example) GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)(which returns all public/private instance properties ).
  • 要获取静态属性的值,请将其null作为第一个参数传递给GetValue
  • 要查看非公共属性,请使用(例如)GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)(返回所有公共/私有实例属性)。

回答by Daan

You can use reflection.

您可以使用反射。

Type typeOfMyObject = myObject.GetType();
PropertyInfo[] properties =typeOfMyObject.GetProperties();

回答by Lucas Jones

You can use Reflectionto do this: (from my library - this gets the names and values)

您可以使用反射来做到这一点:(从我的图书馆 - 这得到名称和值)

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

This thing will not work for properties with an index - for that (it's getting unwieldy):

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

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[]{});
}

Also, to get only public properties: (see MSDN on BindingFlags enum)

此外,仅获取公共属性:(参见 MSDN on BindingFlags enum

/* replace */
PropertyInfo[] props = t.GetProperties();
/* with */
PropertyInfo[] props = t.GetProperties(BindingFlags.Public)

This works on anonymous types, too!
To just get the names:

这也适用于匿名类型!
只需获取名称:

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

And it's just about the same for just the values, or you can use:

并且对于值来说几乎相同,或者您可以使用:

GetDictionaryFromType().Keys
// or
GetDictionaryFromType().Values

But that's a bit slower, I would imagine.

但这有点慢,我想。

回答by Jon Limjap

You could use the System.Reflectionnamespace with the Type.GetProperties()mehod:

您可以将System.Reflection命名空间与方法一起使用Type.GetProperties()

PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);

回答by Singaravelan

I am also facing this kind of requirement.

我也面临这样的需求。

From this discussion I got another Idea,

从这次讨论中我得到了另一个想法,

Obj.GetType().GetProperties()[0].Name

This is also showing the property name.

这也显示了属性名称。

Obj.GetType().GetProperties().Count();

this showing number of properties.

这显示了属性的数量。

Thanks to all. This is nice discussion.

谢谢大家。这是很好的讨论。

回答by DDTBNT

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

This function is for getting list of Class Properties.

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

回答by Ali Osman Mollahüseyino?lu

That's my solution

这就是我的解决方案

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

回答by Imants Volkovs

Here is improved @lucasjones answer. I included improvements mentioned in comment section after his answer. I hope someone will find this useful.

这是改进的@lucasjones 答案。在他的回答之后,我在评论部分提到了改进。我希望有人会发现这很有用。

public static string[] GetTypePropertyNames(object classObject,  BindingFlags bindingFlags)
{
    if (classObject == null)
    {
        throw new ArgumentNullException(nameof(classObject));
    }

        var type = classObject.GetType();
        var propertyInfos = type.GetProperties(bindingFlags);

        return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToArray();
 }

回答by Hymansonkr

Based on @MarcGravell's answer, here's a version that works in Unity C#.

基于@MarcGravell 的回答,这里有一个适用于 Unity C# 的版本。

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