什么时候开始?它是针对我应用它的每个对象运行,还是只运行一次?它能做些什么,或者它的行动受到限制吗?

推荐答案

构造函数什么时候运行?用一个示例来try 一下:

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 instance
Setting value in MyClass instance
Getting attributes for MyClass type
Running constructor

因此,当我们开始判断属性时,就会运行属性构造函数.请注意,属性是从类型获取的,而不是从类型的实例获取的.

.net相关问答推荐

API响应返回null错误. NET MAUI

为什么$NULL在ForEach-Object{}和Foreach()中的行为不同?

使用PowerShell在Windows容器内安装exe

DotNet COM初始化问题

当数据大量分布在微服务中时,我应该如何设计后端?

.NET 中两个子字符串之间的非贪婪正则表达式匹配

Owin Twitter登录-根据验证程序远程证书无效

在 C# 中将字节数组保存为磁盘上的文件的最有效方法是什么?

.Net 中的 Int128?

序列化私有成员数据

我可以在没有两个查询的情况下通过布尔标准将 IEnumerable 一分为二吗?

我不了解应用程序域

获取 .NET 程序集的 AssemblyInformationalVersion 值?

什么是 ToString("N0") 格式?

为什么 C# 不推断我的泛型类型?

为什么会出现编译错误使用未分配的局部变量?

铸造:(NewType)与对象作为NewType

泛型类的默认构造函数的语法是什么?

绑定在代码隐藏中定义的对象

如何在 ASP.NET MVC 中重定向到动态登录 URL