具有多个XmlArrayItemAttribute实例的GetCustomAttribute

问题描述:

我有一个List<TransformationItem>TransformationItem是多类只是基类,如ExtractTextTransformInsertTextTransform具有多个XmlArrayItemAttribute实例的GetCustomAttribute

为了使用内置的XML序列化和反序列化,我必须使用的XmlArrayItemAttribute多个实例,如在http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute%28v=vs.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; 

的问题是,当我使用反射来获取的ElementName与GetCustomAttribute()属性,我得到了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... 
}