簡體   English   中英

如何獲取類的屬性列表?

[英]How to get the list of properties of a class?

如何獲取一個類的所有屬性的列表?

反射; 例如:

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

此外,僅獲取公共屬性:( 請參閱 MSDN 上的 BindingFlags 枚舉

/* 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

但這有點慢,我想。

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

此函數用於獲取類屬性列表。

根據@MarcGravell 的回答,這里有一個適用於 Unity C# 的版本。

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

您可以將System.Reflection命名空間與Type.GetProperties()方法一起使用:

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

這就是我的解決方案

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

試試這個:

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

您可以使用反射。

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

這是改進的@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();
 }

我也面臨這樣的要求。

從這次討論中我得到了另一個想法,

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

這也顯示了屬性名稱。

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

這顯示了屬性的數量。

謝謝大家。 這是很好的討論。

以下代碼將為您提供類屬性/屬性/表列的列表

var Properties = typeof(className).GetProperties().Select(x=>x.Name).Tolist();

這是我如何解決我的

using System;
using System.Reflection;

namespace ReflectionPropertyTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Customer customer = new Customer()
            {
                Id = 1,
                Name = "Salvation",
                DOB = "1 August 2021"
            };
            

            Type myClassType = customer.GetType();
            FieldInfo[] fieldInfos = myClassType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (FieldInfo field in fieldInfos)
            {
                Console.WriteLine($"Name {field.Name}, Value {field.GetValue(customer)}");
            }

            foreach (PropertyInfo prop in customer.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var propertyName = prop.Name;
                Console.WriteLine(propertyName);
                Console.WriteLine(prop.GetValue(customer, null).ToString());
            }
        }
    }

    public class Customer
    {

        public int Id;
        public string Name;
        public string DOB;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM