[英]GetCustomAttribute with multiple instance of XmlArrayItemAttribute
我有一个List<TransformationItem>
。 TransformationItem
只是多个类的基类,例如ExtractTextTransform
和InsertTextTransform
为了使用内置的XML序列化和反序列化,我必须使用XmlArrayItemAttribute
多个实例,如http://msdn.microsoft.com/zh-cn/library/system.xml.serialization.xmlarrayitemattribute%28v=中所述与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
?
找到多个属性后,您需要使用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...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.