具有多个XmlArrayItemAttribute实例的GetCustomAttribute

本文关键字:实例 GetCustomAttribute XmlArrayItemAttribute | 更新日期: 2023-09-27 17:59:18

我有一个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

具有多个XmlArrayItemAttribute实例的GetCustomAttribute

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