2009-06-19 71 views
0

我有幾個基本屬性的類...使用反射來找到[XmlAttribute(「IWantThisValueRightHere」)

[XmlAttribute("MyFirstProperty")] 
public string FirstProperty { get; set; } 

[XmlAttribute("MySecondProperty")] 
public string SecondProperty { get; set; } 

使用反射,我可以通過公共屬性枚舉並得到每個的PropertyInfo對象上述特性的......我現在唯一需要的是一種方法:

  1. 檢測的財產是否有一個XmlAttribute(我想通過PropertyInfo.IsDefined(typeof運算(XmlAttribute這個工程),真的)但想確認)
  2. 獲取XmlAttribute的字符串值

這是如何完成的?

回答

6
object[] attribs = myPropertyInfo.GetCustomAttributes(typeof(XmlAttribute),false); 
bool doesPropertyHaveAttrib =attribs.Length > 0; 
string name = (XmlAttribute)(attribs[0].AttributeName); 

好評由喬爾在評論。我的錯。固定。

+0

。 System.Object沒有AttributeName屬性。 – 2009-06-19 18:19:29

0

我目前使用這種方法:

'獲取的屬性

 Dim pi() As PropertyInfo = arguments.SourceObject.GetType.GetProperties(BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public Or BindingFlags.GetProperty) 

' 獲得屬性的屬性

暗淡pitem作爲的PropertyInfo = PI(0)

  Dim vobj() As Object = pitem.GetCustomAttributes(GetType(ValidationSettingsBaseAttribute), False) 


      Dim attr As ValidationSettingsBaseAttribute= TryCast(vobj(0), ValidationSettingsBaseAttribute) 
1

我意識到這是一個老問題。今天遇到了同樣的問題,這裏提供的解決方案都沒有奏效。尤其是看到建議的解決方案Attribute.GetCustomAttributes(typeof(XmlAttribute),false) 如何引發異常,因爲XmlAttribute不是從System.Attribute派生的。相反,你應該檢查XmlAttributeAttribute

以供將來參考,這是使用反射來檢查XmlAttribute正確和工作方式:你將不得不做最後一行一些鑄造

PropertyInfo[] objProperties = obj.GetProperties(); 

foreach (var prop in objProperties) 
{ 
Attribute[] propXmlAttr = Attribute.GetCustomAttributes(prop, typeof(XmlAttributeAttribute), false); 
if (propXmlAttr.Length > 0) 
    string myAttribute = propValue.ToString()); 
}