gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:59 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com