[英]GetCustomAttribute with multiple instance of XmlArrayItemAttribute
I have a List<TransformationItem>
. 我有一个
List<TransformationItem>
。 TransformationItem
is just base class for multiple classes, such as ExtractTextTransform
and InsertTextTransform
TransformationItem
只是多个类的基类,例如ExtractTextTransform
和InsertTextTransform
In order to use built-in XML Serialization and Deserialization, I have to use multiple instance of XmlArrayItemAttribute
, as described in http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute%28v=vs.80%29.aspx 为了使用内置的XML序列化和反序列化,我必须使用
XmlArrayItemAttribute
多个实例,如http://msdn.microsoft.com/zh-cn/library/system.xml.serialization.xmlarrayitemattribute%28v=中所述与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.
您可以应用XmlArrayItemAttribute或XmlElementAttribute的多个实例来指定可以插入到数组中的对象的类型。
Here is my code: 这是我的代码:
[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;
The problem is, when I use reflection to get ElementName attribute with GetCustomAttribute()
, I got AmbiguousMatchException
. 问题是,当我使用反射通过
GetCustomAttribute()
获取ElementName属性时,得到了AmbiguousMatchException
。
How can I solve this, say, get the ElementName
? 我该如何解决这个问题,例如,获取
ElementName
?
As more than one attribute was found, you need to use ICustomAttributeProvider.GetCustomAttributes()
. 找到多个属性后,您需要使用
ICustomAttributeProvider.GetCustomAttributes()
。 Otherwise, the Attribute.GetCustomAttribute()
method throws an AmbiguousMatchException
, as it doesn't know which attribute to select. 否则,
Attribute.GetCustomAttribute()
方法将抛出AmbiguousMatchException
,因为它不知道选择哪个属性。
I like to wrap this as an extension method, eg: 我喜欢将其包装为扩展方法,例如:
public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this ICustomAttributeProvider provider, bool inherit = false)
where TAttribute : Attribute
{
return provider
.GetCustomAttributes(typeof(TAttribute), inherit)
.Cast<TAttribute>();
}
Called like: 像这样称呼:
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.