具有多个XmlArrayItemAttribute实例的GetCustomAttribute

时间:2011-06-17 10:34:51

标签: c# reflection custom-attributes

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

为了使用内置的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;

问题是,当我使用反射来获取GetCustomAttribute()的ElementName属性时,我得到了AmbiguousMatchException

如何解决这个问题,比如说,获取ElementName

1 个答案:

答案 0 :(得分:6)

由于找到了多个属性,您需要使用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...
}