gpt4 book ai didi

c# - MethodBase.IsConstructor 无法按照静态构造函数指定的方式工作

转载 作者:行者123 更新时间:2023-12-02 21:43:22 25 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/

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