gpt4 book ai didi

c# - 查看/检索属性

转载 作者:行者123 更新时间:2023-11-30 15:40:14 25 4
gpt4 key购买 nike

在一个类中,我有以下代码:

/// <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;
}
}

仅使用反射,是否可以检索这些属性?我在相应的 Type 上看到了“GetCustomAttributes(),但并没有得到太多的快乐。

最佳答案

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

typeof(MyClass).GetProperty("Items").GetCustomAttributes(typeof(XmlElementAttribute), false);

或更完整(记得导入 System.Linq 以便 Cast<> 和 ToArray() 工作):

XmlElementAttribute[] attribs = typeof(TheType)
.GetProperty("Items")
.GetCustomAttributes(typeof(XmlElementAttribute), false)
.Cast<XmlElementAttribute>()
.ToArray();

关于c# - 查看/检索属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9501346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com