如何获取变量属性值?

Van*_*dze 3 c# attributes

我的目标是获取类属性及其值.

例如,如果我有一个属性'Bindable'来检查属性是否可绑定:

public class Bindable : Attribute
{
    public bool IsBindable { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个Person类:

public class Person
{
    [Bindable(IsBindable = true)]
    public string FirstName { get; set; }

    [Bindable(IsBindable = false)]
    public string LastName { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

如何获取FirstName和LastName的'Bindable'属性值?

    public void Bind()
    {
        Person p = new Person();

        if (FirstName property is Bindable)
            p.FirstName = "";
        if (LastName property is Bindable)
            p.LastName = "";
    }
Run Code Online (Sandbox Code Playgroud)

谢谢.

Jon*_*eet 6

实例没有单独的属性 - 您必须询问其成员的类型(例如Type.GetProperties),并询问这些成员的属性(例如PropertyInfo.GetCustomAttributes).

编辑:根据评论,MSDN上有关于属性的教程.