gpt4 book ai didi

c# - MethodBase.IsConstructor 不能按照静态构造函数指定的那样工作

转载 作者:行者123 更新时间:2023-12-02 04:44:57 26 4
gpt4 key购买 nike

只是一个简单的观察。 property MethodBase.IsConstructor不适用于 static 构造函数,并且文档没有提及这个事实(引用:“true 如果此方法是由 ConstructorInfo 对象”)。

示例:

static class Program
{
static void Main()
{
ConstructorInfo ci = typeof(Test).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { }, null);
Console.WriteLine(ci is ConstructorInfo); // silly; writes True
Console.WriteLine(ci.IsConstructor); // ?? writes False
}
}

static class Test
{
static Test()
{
Console.WriteLine("I am your static constructor");
}
}

问题:为什么?错误或不完整的规范?

最佳答案

“静态构造函数”实际上只是 C# 术语。在 .NET 本身中,有一个类型初始值设定项(根据 Type.TypeInitializer )。一个类型可以有一个类型初始值设定项,而无需在 C# 中声明静态构造函数——例如用于静态变量初始化。

在源 C# 中使用静态构造函数有两个作用:

  • 它删除了 beforefieldinit来自类型的标志,可能会改变时间
  • 将代码添加到类型初始化器中

因此,虽然它由 ConstructorInfo 表示,但我对 IsConstructor 返回 false 并不感到特别惊讶,因为它不是 CLR 术语中的构造函数。它是由 ConstructorInfo 对象表示的非构造函数 :) 如果将文档改写为“如果此方法是实例构造函数”,以及如果 GetConstructor 没有归还它(因为这很不一致,IMO)。

诚然,GetConstructor 的文档说明:

To get the class initializer (.cctor) using this method overload, you must specify BindingFlags.Static | BindingFlags.NonPublic. You can also get the class initializer using the TypeInitializer property.

...所以他们在那里不称其为构造函数。

关于c# - MethodBase.IsConstructor 不能按照静态构造函数指定的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19974986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com