【发布时间】:2021-10-11 17:44:18
【问题描述】:
假设我们有两个类:
MainClass:
public class MainClass
{
[CustomAttribute("John Smith", 55)]
ItemClass ic = new ItemClass();
}
ItemClass:
public class ItemClass
{
public void TestMethod()
{
// I want to get the "John Smith" and 55 from here
}
}
还有一个自定义属性CustomAttribute:
public class CustomAttribute : Attribute
{
public string Name;
public int Age;
public CustomAttribute(string name, string age)
{
this.Name = name;
this.Age = age;
}
}
有什么方法可以从我的 ItemClass 的实例中获取该属性(在 MainClass 中定义)?
换句话说,我怎样才能从TestMethod()内部得到"John Smith"和55?
【问题讨论】:
-
看起来很奇怪。为什么你不使用构造函数或初始化器来分配属性?
-
这能回答你的问题吗? Reflection - get attribute name and value on property 和 How to get Attribute Value for property 和 Custom attribute on property - Getting type and value 和 Get attribute values from property and list values without knowing the attribute type 和 get property value from object using custom attribute
-
@Serge 是的,我知道这是一个奇怪的请求,但我只是想知道这是否可能。我可能最终会使用构造函数。
标签: c# attributes custom-attributes system.reflection