具有 XmlArrayItemAttribute 的多个实例的 GetCustomAttribute
我有一个 List
。TransformationItem
只是多个类的基类,例如 ExtractTextTransform
和 InsertTextTransform
为了使用内置的 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 属性时,我得到了 AmbigouslyMatchException
。
我该如何解决这个问题,比如说获取 ElementName
?
I have a List<TransformationItem>
.TransformationItem
is just base class for multiple classes, such as ExtractTextTransform
and 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
You can apply multiple instances of the XmlArrayItemAttribute or XmlElementAttribute to specify types of objects that can be inserted into the array.
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
.
How can I solve this, say, get the ElementName
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于找到了多个属性,您需要使用
ICustomAttributeProvider.GetCustomAttributes()
。否则,Attribute.GetCustomAttribute()
方法会抛出AmbigouslyMatchException
,因为它不知道要选择哪个属性。我喜欢将其包装为扩展方法,例如:
调用方式如下:
As more than one attribute was found, you need to use
ICustomAttributeProvider.GetCustomAttributes()
. Otherwise, theAttribute.GetCustomAttribute()
method throws anAmbiguousMatchException
, as it doesn't know which attribute to select.I like to wrap this as an extension method, e.g.:
Called like: