2011-08-29 61 views
0

我需要使用反射閱讀使用反射

例如讀取屬性的屬性的屬性的屬性,我得到如下:

[XmlElement("Id")] 
    [CategoryAttribute("Main"), ReadOnly(true), 
    Description("This property is auto-generated")] 
    [RulesCriteria("ID")] 
    public override string Id 
    { 
     get { return _ID; } 
     set 
     { 
      _ID = value; 
     } 
    } 

我想要得到的「只讀」值此屬性使用反射 任何人都可以幫助

回答

0

很難爲您的案例編寫代碼而不知道類型名稱。希望下面的例子幫助。

using System; 
using System.Reflection; 

public class Myproperty 
{ 
    private string caption = "Default caption"; 
    public string Caption 
    { 
     get{return caption;} 
     set {if(caption!=value) {caption = value;} 
     } 
    } 
} 

class Mypropertyinfo 
{ 
    public static int Main(string[] args) 
    { 
     Console.WriteLine("\nReflection.PropertyInfo"); 

     // Define a property. 
     Myproperty Myproperty = new Myproperty(); 
     Console.Write("\nMyproperty.Caption = " + Myproperty.Caption); 

     // Get the type and PropertyInfo. 
     Type MyType = Type.GetType("Myproperty"); 
     PropertyInfo Mypropertyinfo = MyType.GetProperty("Caption"); 

     // Get and display the attributes property. 
     PropertyAttributes Myattributes = Mypropertyinfo.Attributes; 

     Console.Write("\nPropertyAttributes - " + Myattributes.ToString()); 

     return 0; 
    } 
} 

MSDN

+0

所以我怎麼就知道只讀是真的還是假的? – Yasser

+0

看看這裏例子18-2 http://oreilly.com/catalog/progcsharp/chapter/ch18.html – CharithJ

+0

它是非常有用的,但在:foreach(屬性中的對象屬性) BugFixAttribute bfa =(BugFixAttribute)屬性; Console.WriteLine(「\ nBugID:{0}」,bfa.BugID); Console.WriteLine(「程序員:{0}」,bfa.Programmer); Console.WriteLine(「Date:{0}」,bfa.Date); Console.WriteLine(「Comment:{0}」,bfa.Comment); } 我想在這個循環中做一個條件來捕捉屬性只讀和知道它的價值,你得到我嗎? – Yasser

0
public static bool PropertyReadOnlyAttributeValue(PropertyInfo property) 
{ 
    ReadonlyAttribute attrib = Attribute.GetCustomAttribute(property, typeof(ReadOnlyAttribute)); 
    return attrib != null && attrib.IsReadOnly; 
} 

public static bool PropertyReadOnlyAttributeValue(Type type, string propertyName) 
{ 
    return PropertyReadOnlyAttributeValue(type.GetProperty(propertyName)); 
} 

public static bool PropertyReadOnlyAttributeValue(object instance, string propertyName) 
{ 
    if (instance != null) 
    { 
     Type type = instance.GetType(); 
     return PropertyReadOnlyAttributeValue(type, propertyName); 
    } 
    return false; 
}