使用Reflection查找[XmlAttribute("IWantThisValueRightHere")]

Bra*_*don 0 c# reflection

我有一个基本属性的课程......

[XmlAttribute("MyFirstProperty")]
public string FirstProperty { get; set; }

[XmlAttribute("MySecondProperty")]
public string SecondProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)

使用Reflection,我可以枚举公共属性并获取上面每个属性的PropertyInfo对象......我现在唯一需要的是:

  1. 检测属性是否有XmlAttribute(我认为这可以通过PropertyInfo.IsDefined(typeof(XmlAttribute),true),但是想确定)
  2. 获取XmlAttribute的字符串值

这是怎么做到的?

BFr*_*ree 6

 object[] attribs = myPropertyInfo.GetCustomAttributes(typeof(XmlAttribute),false);
 bool doesPropertyHaveAttrib =attribs.Length > 0; 
 string name = (XmlAttribute)(attribs[0].AttributeName);
Run Code Online (Sandbox Code Playgroud)

Joel在评论中提出的要点.我的错.固定.