C# 查看/检索属性

C# 查看/检索属性,c#,reflection,C#,Reflection,在类中,我有以下代码: /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Errors", typeof(ErrorsType))] [System.Xml.Serialization.XmlElementAttribute("Success", typeof(SuccessType))] [System.Xml.Serialization.XmlElementAttribute("Warnings", typ

在类中,我有以下代码:

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Errors", typeof(ErrorsType))]
[System.Xml.Serialization.XmlElementAttribute("Success", typeof(SuccessType))]
[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items {
    get {
        return this.itemsField;
    }
    set {
        this.itemsField = value;
    }
}
//
[System.Xml.Serialization.xmlementAttribute(“Errors”,typeof(ErrorsType))]
[System.Xml.Serialization.xmlementAttribute(“Success”,typeof(SuccessType))]
[System.Xml.Serialization.XmlElementAttribute(“警告”,类型为(警告类型))]
公共对象[]项{
得到{
返回此.itemsField;
}
设置{
this.itemsField=值;
}
}
仅使用反射,是否可以检索这些属性?
我在相应的
类型
上看到了“
GetCustomAttributes()
,但没有得到多少乐趣。

您需要从属性中检索属性,而不是从类型本身,如下所示:

typeof(MyClass).GetProperty("Items").GetCustomAttributes(typeof(XmlElementAttribute), false);
或更完整(请记住导入System.Linq以便Cast和ToArray()工作):

xmlementattribute[]attribs=typeof(类型)
.GetProperty(“项目”)
.GetCustomAttributes(typeof(xmlementAttribute),false)
.Cast()
.ToArray();
XmlElementAttribute[] attribs = typeof(TheType)
                  .GetProperty("Items")
                  .GetCustomAttributes(typeof(XmlElementAttribute), false)
                  .Cast<XmlElementAttribute>()
                  .ToArray();