Programing

클래스의 속성 목록을 얻는 방법은 무엇입니까?

crosscheck 2020. 10. 4. 10:29
반응형

클래스의 속성 목록을 얻는 방법은 무엇입니까?


클래스의 모든 속성 목록을 얻으려면 어떻게해야합니까?


반사; 예를 들어 :

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):) (모든 공개 / 개인 인스턴스 속성을 반환 함)를 사용합니다.

이를 위해 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;
}

인덱스가있는 속성에서는이 기능이 작동하지 않습니다.

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 enum의 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

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


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.


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

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

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

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

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

You can use reflection.

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

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.


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

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

참고URL : https://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-a-class

반응형