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


当前回答

你可以使用这个系统。使用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;
}

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

PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
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;
}

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

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

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

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