【问题标题】:GetCustomAttribute with multiple instance of XmlArrayItemAttribute具有多个 XmlArrayItemAttribute 实例的 GetCustomAttribute
【发布时间】:2011-06-17 10:34:50
【问题描述】:

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

【问题讨论】:

    标签: c# reflection custom-attributes


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      相关资源
      最近更新 更多