开发者

How to get variable attribute values?

My goal is to get class properties attribute and it's values.

For example, if I have an attrib开发者_运维技巧ute 'Bindable' to check if property is bindable:

public class Bindable : Attribute
{
    public bool IsBindable { get; set; }
}

And I have a Person class:

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

    [Bindable(IsBindable = false)]
    public string LastName { get; set; } 
}

How can I get FirstName's and LastName's 'Bindable' attribute values?

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

        if (FirstName property is Bindable)
            p.FirstName = "";
        if (LastName property is Bindable)
            p.LastName = "";
    }

Thanks.


Instances don't have separate attributes - you have to ask the type for its members (e.g. with Type.GetProperties), and ask those members for their attributes (e.g. PropertyInfo.GetCustomAttributes).

EDIT: As per comments, there's a tutorial on MSDN about attributes.


You can try by this way:

     public class Bindable : Attribute
        {
            public bool IsBindable { get; set; }
        }

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

            [Bindable(IsBindable = false)]
            public string LastName { get; set; }
        }

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

                foreach (PropertyInfo property in p.GetType().GetProperties())
                {

                   try
                   {
                       Bindable _Attribute = (Bindable)property.GetCustomAttributes(typeof(Bindable), false).First();

                       if (_Attribute.IsBindable)
                       {
                            //TODO
                       }
                    }
                    catch (Exception) { }
                }
            }
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜