【发布时间】: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.GetCustomAttributes 的unsafe 重载中)。一旦通过了构造函数的第一行,我在 Locals 窗口上有以下内容:
问题:
为什么
this的值是从ToString返回的值?MyFirst没有价值。它会在什么时候[编辑:即System.CustomAttribute中的什么方法初始化此属性]? (在调试器中看不到它发生,我不知道为什么)。
【问题讨论】:
-
你没有在构造函数中设置 First,就像你在 Second: Second = "hello";
-
使用您编辑的代码,在最后一行之后 MyFirst 应该具有“自定义”作为值。
-
@αNerd,乍得,我编辑了我的第二个问题。
标签: c# attributes