2011-08-16 23 views
2

我的目标是获取类属性及其值。如何获取可变属性值?

举例来说,如果我有一个属性“可绑定”,以检查是否属性是可绑定:

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

而且我有一个Person类:

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

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

我怎样才能名字的和姓氏的'Bindable'属性值?

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

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

谢谢。

回答

5

实例没有单独的属性 - 你要问的为它的成员(例如用Type.GetProperties),并要求这些成员的属性(例如PropertyInfo.GetCustomAttributes)。

编辑:根据意见,有关于属性的tutorial on MSDN

+1

有一个不错的[属性教程](http://msdn.microsoft.com/en-us/library/aa288454.aspx)覆盖这个MSDN上。 –

+0

@克里斯:谢谢,将编辑。 –

2

您可以通过这种方式尝试:

 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) { } 
       } 
      } 
     }