- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个 List<TransformationItem>
. TransformationItem
只是多个类的基类,例如ExtractTextTransform
和 InsertTextTransform
为了使用内置的 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/
XmlArrayAttribute 和 XmlArrayItemAttribute 有什么区别?请解释双方(即序列化和反序列化)。 最佳答案 一个简短的回答 - 使用 XmlArrayAttribut
我有一个 List . TransformationItem只是多个类的基类,例如ExtractTextTransform和 InsertTextTransform 为了使用内置的 XML 序列化和反
我是一名优秀的程序员,十分优秀!