【问题标题】:Get attributes associated with the class's instance from within the class从类中获取与类实例关联的属性
【发布时间】: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

【问题讨论】:

标签: c# attributes custom-attributes system.reflection


【解决方案1】:

应该像这样工作(未经测试):

public class ItemClass
{
    public void TestMethod()
    {
        // I want to get the "John Smith" and 55 from here
        CustomAttribute ca = typeof(MainClass)
            .GetField("ic", BindingFlags.Private | BindingFlags.Instance)
            .GetCustomAttributes(typeof(CustomAttribute), false)
            .FirstOrDefault() as CustomAttribute;

        Console.WriteLine("Name: {0}, Age: {1}", ca.Name, ca.Age);
    }
}

【讨论】:

  • GetField 可以返回 null:在 C# 6+ 中首选 nameof(ic),否则进行 null 检查。
  • @OlivierRogier nameof(ic) 不会编译。是nameof(MainClass.ic) 建议同时进行空值检查非常亮,因为如果该字段的nameof 编译,GetField 不能返回空值。所以谢谢你的聪明输入。
  • 我想我应该在我原来的问题中提到这一点,但一般情况下可以完全做到这一点吗?基本上,有没有办法做到这一点,不需要TestMethod 知道MainClass"ic"
  • 如果您要读取其属性的字段在 MainClass(或任何其他类)中,您必须了解该类和字段名称。
  • 唯一可能不知道字段(或属性?)名称和类的方法是遍历所有已加载程序集的所有类型的所有成员并获取它们的自定义属性。这是可行的,但有点奇怪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多