【问题标题】:Value of a CustomAttributeCustomAttribute 的值
【发布时间】:2016-09-28 22:36:31
【问题描述】:

我正在尝试了解自定义属性的工作原理。 我有以下代码(主要基于this SO答案):

class Test
{
    public static void Main()
    {
        Console.WriteLine("before class constructor");
        var test = new TestClass();
        Console.WriteLine("after class constructor");

        Attribute[] attributes = Attribute.GetCustomAttributes(test.GetType()); 
    }
}

public class TestClassAttribute : Attribute
{
    public TestClassAttribute()
    {
        Second = "hello";
        Console.WriteLine("I am here. I'm the attribute constructor!");
    }
    public String First { get; set; }
    public String Second { get; set; }
    public override String ToString()
    {
        return String.Format("MyFirst: {0}; MySecond: {1}", First, Second);
    }
}

[TestClass(First = "customized")]
public class TestClass
{
    public int Foo { get; set; }
}

我在Main 的最后一行设置了一个断点,并使用调试器深入研究了源代码,直到调用了TestClassAttribute 构造函数(发生在CustomAttribute.GetCustomAttributesunsafe 重载中)。一旦通过了构造函数的第一行,我在 Locals 窗口上有以下内容:

问题:

  1. 为什么this 的值是从ToString 返回的值?

  2. MyFirst 没有价值。它会在什么时候[编辑:即System.CustomAttribute 中的什么方法初始化此属性]? (在调试器中看不到它发生,我不知道为什么)。

【问题讨论】:

  • 你没有在构造函数中设置 First,就像你在 Second: Second = "hello";
  • 使用您编辑的代码,在最后一行之后 MyFirst 应该具有“自定义”作为值。
  • @αNerd,乍得,我编辑了我的第二个问题。

标签: c# attributes


【解决方案1】:

ToString 确实被设计为(阅读:被设计)作为调试工具,这就是为什么它在 Locals 窗口中显示为本地值。

似乎属性的任何名称参数都是在构造函数运行之后的赋值。大致上,我认为编译器是这样解释的:

TestClassAttribute instance = new TestClassAttribute();
instance.First = "customized";

【讨论】:

    猜你喜欢
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多