我有一个基本属性的课程......
[XmlAttribute("MyFirstProperty")]
public string FirstProperty { get; set; }
[XmlAttribute("MySecondProperty")]
public string SecondProperty { get; set; }
使用Reflection,我可以枚举公共属性并获取上面每个属性的PropertyInfo对象......我现在唯一需要的是:
这是怎么做到的?
答案 0 :(得分:6)
object[] attribs = myPropertyInfo.GetCustomAttributes(typeof(XmlAttribute),false);
bool doesPropertyHaveAttrib =attribs.Length > 0;
string name = (XmlAttribute)(attribs[0].AttributeName);
乔尔在评论中提出了很好的观点。我的错。固定的。
答案 1 :(得分:1)
我意识到这是一个老问题。今天遇到同样的问题,这里提供的解决方案都没有奏效。特别是看看提议的解决方案Attribute.GetCustomAttributes(typeof(XmlAttribute),false)
抛出异常,因为XmlAttribute不是从System.Attribute派生的。相反,您应该检查XmlAttributeAttribute
。
为了将来参考,这是使用反射检查XmlAttribute的正确和有效方法:
PropertyInfo[] objProperties = obj.GetProperties();
foreach (var prop in objProperties)
{
Attribute[] propXmlAttr = Attribute.GetCustomAttributes(prop, typeof(XmlAttributeAttribute), false);
if (propXmlAttr.Length > 0)
string myAttribute = propValue.ToString());
}
答案 2 :(得分:0)
我目前使用这种方法:
'获取属性
Dim pi() As PropertyInfo = arguments.SourceObject.GetType.GetProperties(BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public Or BindingFlags.GetProperty)
'获取属性的属性
dim pitem As PropertyInfo = pi(0)
Dim vobj() As Object = pitem.GetCustomAttributes(GetType(ValidationSettingsBaseAttribute), False)
Dim attr As ValidationSettingsBaseAttribute= TryCast(vobj(0), ValidationSettingsBaseAttribute)