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


当前回答

你可以使用反射。

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

其他回答

下面的代码将提供类属性/属性/表列的列表

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

你可以使用这个系统。使用Type.GetProperties()方法的反射命名空间:

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

我也面临着这样的要求。

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

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

这也显示了属性名。

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

这显示了属性的数量。

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

这是改进后的@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();
 }

你可以使用反射。

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