构造函数何时运行?尝试一个示例:
class Program{ static void Main(string[] args) { Console.WriteLine("Creating MyClass instance"); MyClass mc = new MyClass(); Console.WriteLine("Setting value in MyClass instance"); mc.Value = 1; Console.WriteLine("Getting attributes for MyClass type"); object[] attributes = typeof(MyClass).GetCustomAttributes(true); }}[AttributeUsage(AttributeTargets.All)]public class MyAttribute : Attribute{ public MyAttribute() { Console.WriteLine("Running constructor"); }}[MyAttribute]class MyClass{ public int Value { get; set; }}
输出是什么?
Creating MyClass instanceSetting value in MyClass instanceGetting attributes for MyClass typeRunning constructor
因此,当我们开始检查属性时,将运行属性构造函数。请注意,属性是从类型而不是类型的实例中获取的。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)