c# - 为什么属性被延迟实例化?

标签 c# .net attributes lazy-initialization

我发现 C# 中的属性似乎是延迟实例化的。

[A(123)]
class A : Attribute
{
    public A(int b)
    {
        GetType().GetCustomAttributes(true);
    }
}

在此示例中,创建新的 A 实例会导致 StackOverflowException,但如果我删除对 GetCustomAttributes() 的调用,则执行正常进行。

这是为什么呢?对我来说,当属性装饰的类正确初始化时,更有意义。

最佳答案

为什么运行时需要在请求之前实例化类上的所有属性?这就像问为什么运行时不提前创建我的类的实例,以防万一我以后想使用它。

属性是类的元数据,它们不会以任何方式影响类的工作。只有请求属性的代码关心它,其他人都不关心。所以目前的行为确实有道理。

关于c# - 为什么属性被延迟实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3624075/

相关文章:

c# - 更漂亮的不格式化 Unity C# 代码 - "Cannot format Movement.cs"

c# - 如何通过linq从json获取子数据

c# - 使用 VisualStyles 的控件边框颜色

.net - AssemblyVersion、AssemblyFileVersion 和 AssemblyInformationalVersion 之间有什么区别?

python - Python 中的属性访问 : first slots, 然后 __dict__?

c# - 如何从 Windows 窗体应用程序检查 session 变量是否存在

c# - 生成错误 : "The process cannot access the file because it is being used by another process"

c# - Entity Framework 嵌套导航属性仅计数

c# - Excel VSTO + C# .NET + 创建数据透视表

c# - 使属性彼此不兼容?