c# – 使用反射为单个属性获取XmlElementAttribute的每个实例
发布时间:2020-12-16 01:48:08 所属栏目:百科 来源:网络整理
导读:我正在尝试列出Item可能包含的可能类型.但是我陷入困境,我无法调用Item.GetType()来遍历其属性,因为这只会返回它已经包含的类型的属性. 我尝试过TypeDescriptor.GetProperties(…)但是Attributes容器只包含一个XmlElementAttribute实例,它是应用于属性的最后
我正在尝试列出Item可能包含的可能类型.但是我陷入困境,我无法调用Item.GetType()来遍历其属性,因为这只会返回它已经包含的类型的属性.
我尝试过TypeDescriptor.GetProperties(…)但是Attributes容器只包含一个XmlElementAttribute实例,它是应用于属性的最后一个实例(在本例中为WindowTemplate) 这一定是微不足道的,但我找不到任何解决我在线问题的方法. [System.Xml.Serialization.XmlElementAttribute("ChildTemplate",typeof(ChildTmpl),Order = 1)] [System.Xml.Serialization.XmlElementAttribute("WindowTmeplate",typeof(WindowTmpl),Order = 1)] public object Item { get { return this.itemField; } set { this.itemField = value; } } 解决方法
您不能使用TypeDescriptor,因为System.ComponentModel总是折叠属性.您必须使用PropertyInfo和Attribute.GetCustomAttributes(property,attributeType):
var property = typeof (Program).GetProperty("Item"); Attribute[] attribs = Attribute.GetCustomAttributes( property,typeof (XmlElementAttribute)); 如果它更容易,数组实际上将是一个XmlElementAttribute []: XmlElementAttribute[] attribs = (XmlElementAttribute[]) Attribute.GetCustomAttributes(property,typeof (XmlElementAttribute)); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容