Tua*_*-Vu 1 c# reflection custom-attributes
我有一个List<TransformationItem>.TransformationItem只是多个类的基类,例如ExtractTextTransform和InsertTextTransform
为了使用内置的XML序列化和反序列化,我必须使用多个实例XmlArrayItemAttribute,如http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute%28v=vs中所述.0.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;
Run Code Online (Sandbox Code Playgroud)
问题是,当我使用反射来获取ElementName属性时GetCustomAttribute(),我得到了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>();
}
Run Code Online (Sandbox Code Playgroud)
被称为:
var attribute = typeof(TransformationItem)
.GetAttributes<XmlArrayItemAttribute>(true)
.Where(attr => !string.IsNullOrEmpty(attr.ElementName))
.FirstOrDefault();
if (attribute != null)
{
string elementName = attribute.ElementName;
// Do stuff...
}
Run Code Online (Sandbox Code Playgroud)