[英]GetCustomAttribute with multiple instance of XmlArrayItemAttribute
我有一個List<TransformationItem>
。 TransformationItem
只是多個類的基類,例如ExtractTextTransform
和InsertTextTransform
為了使用內置的XML序列化和反序列化,我必須使用XmlArrayItemAttribute
多個實例,如http://msdn.microsoft.com/zh-cn/library/system.xml.serialization.xmlarrayitemattribute%28v=中所述與80%29.aspx
您可以應用XmlArrayItemAttribute或XmlElementAttribute的多個實例來指定可以插入到數組中的對象的類型。
這是我的代碼:
[XmlArrayItem(Type = typeof(Transformations.EvaluateExpressionTransform))]
[XmlArrayItem(Type = typeof(Transformations.ExtractTextTransform))]
[XmlArrayItem(Type = typeof(Transformations.InsertTextTransform))]
[XmlArrayItem(Type = typeof(Transformations.MapTextTransform))]
[XmlArrayItem(Type = typeof(Transformations.ReplaceTextTransform))]
[XmlArrayItem(Type = typeof(Transformations.TextItem))]
[XmlArrayItem(ElementName = "Transformation")]
public List<Transformations.TransformationItem> transformations;
問題是,當我使用反射通過GetCustomAttribute()
獲取ElementName屬性時,得到了AmbiguousMatchException
。
我該如何解決這個問題,例如,獲取ElementName
?
找到多個屬性后,您需要使用ICustomAttributeProvider.GetCustomAttributes()
。 否則, Attribute.GetCustomAttribute()
方法將拋出AmbiguousMatchException
,因為它不知道選擇哪個屬性。
我喜歡將其包裝為擴展方法,例如:
public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this ICustomAttributeProvider provider, bool inherit = false)
where TAttribute : Attribute
{
return provider
.GetCustomAttributes(typeof(TAttribute), inherit)
.Cast<TAttribute>();
}
像這樣稱呼:
var attribute = typeof(TransformationItem)
.GetAttributes<XmlArrayItemAttribute>(true)
.Where(attr => !string.IsNullOrEmpty(attr.ElementName))
.FirstOrDefault();
if (attribute != null)
{
string elementName = attribute.ElementName;
// Do stuff...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.