programing

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

oldcodes 2023. 5. 29. 11:09
반응형

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

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

반영; 예를 들어:

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에 대한 제1의 논거로서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[]{});
}

또한 공용 속성만 가져오려면: (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

하지만 그건 좀 더 느리다고 생각합니다.

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

이 함수는 클래스 속성 목록을 가져오기 위한 것입니다.

@MarcGravel의 답변을 바탕으로 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);

사용해 보십시오.

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

다음 코드는 클래스 속성/속성/테이블 열 목록을 제공합니다.

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

그게 내 해결책입니다.

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

반사를 사용할 수 있습니다.

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

속성 수를 표시합니다.

모두에게 감사합니다.이것은 좋은 토론입니다.

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

반응형