c# - 具有多个 XmlArrayItemAttribute 实例的 GetCustomAttribute

标签 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 中所述

You can apply multiple instances of the XmlArrayItemAttribute or XmlElementAttribute to specify types of objects that can be inserted into the array.

这是我的代码:

[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...
}    

关于c# - 具有多个 XmlArrayItemAttribute 实例的 GetCustomAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6384501/

相关文章:

c# - MVC4 WebAPI 过滤器 : any way to stub Filter. 顺序?

c# - Unity currentActivity 在场景变化时会变化吗?

python - 如何在Python中调用子类对象的未绑定(bind)方法

c# - 如何知道参数是数组?

java - 通用对象创建方法的返回类型

c# - 自定义 Api 授权忽略 AllowAnonymous

mysql - 数据库动态字段(自定义属性)

c# - 使用 C# 在 Word 中插入符号

c# - 我可以避免使用非常大的 'switch' block 来访问 400 个程序代码块吗?

c# - 在 C# 中解密用 PHP openssl_encrypt 加密的字符串