繁体   English   中英

通过PropertyInfo获取属性的名称

[英]Get property's name by PropertyInfo

我有这样的课:

public abstract class SomeClass<T> where T: new() {
    ...
    public void GetData() {
        ...
        var cur = new T();
        var properties = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();
    ...
    }
}

其中T可以像

public class {
    ...
    public int SomeField {get; set;}
    ...
}

如何通过属性获取“ SomeField”?

如果我调用properties[i].Name得到“ Int32”。

在属性中有RuntimePropertyInfo成员,但我无权访问。

这很好用:

public class SomeType
{
    public int SomeField { get; set; }
}
class Program
{
    static void GetData<T>()
    {
        var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();
        var firstPropertyName = properties[0].Name;
        Console.WriteLine(firstPropertyName);
    }
    static void Main()
    {
        GetData<SomeType>();
    }
}

我认为您正在访问.PropertyType.Name而不是.Name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM