在Visual Studio 2012中,有一条规则说:静态构造函数应该是私有的,但编译器不允许这样做.所以无论如何我们可以创建公共静态构造函数吗?

更新:在链接中,它说"如果静态构造函数不是私有的,它可以由系统以外的代码调用." 它让我想到了这个问题.
你必须省略public/ private修饰符:
public class Test
{
static Test()
{
}
}
Run Code Online (Sandbox Code Playgroud)
实际上private静态构造函数的概念有点脆弱,因为静态构造函数只能由CLR(运行时)调用(并且可以调用).因此,private可能只是因为每个方法都必须有一个修饰符,而不是因为它意味着什么(为了清楚说明:私有非静态构造函数可以由定义它的类调用,而静态构造函数不能直接由定义它的类调用)
请注意,从技术上讲,通过直接编写IL代码,您可以创建静态构造函数public......然后您可以将其称为"正常"方法......并且发生了不好的事情 ......为了说清楚:
基础源代码:
using System;
using System.Linq;
using System.Reflection;
public class Program
{
static void Main(string[] args)
{
}
}
public class Test
{
static Test()
{
ConstructorInfo ci = typeof(Test).GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).Single();
Console.WriteLine("Static constructor: IsPublic: {0}, IsPrivate: {1}", ci.IsPublic, ci.IsPrivate);
}
}
Run Code Online (Sandbox Code Playgroud)
使用Visual Studio编译它.
从开发人员命令提示符:
ildasm YourExe.exe /out:test.il
Run Code Online (Sandbox Code Playgroud)
将Main身体改为
.entrypoint
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
// we call manually the cctor (the static constructor)
call void Test::.cctor()
IL_0001: ret
Run Code Online (Sandbox Code Playgroud)
然后将Test.cctor签名更改为
.method public hidebysig specialname rtspecialname static void .cctor()cil managed
(见public?)
现在
.method public hidebysig specialname rtspecialname static
void .cctor() cil managed
Run Code Online (Sandbox Code Playgroud)
输出:
ilasm test.il
test.exe
Run Code Online (Sandbox Code Playgroud)
静态构造函数已执行两次:您调用.cctor加上CLR 对其执行的自动调用.cctor.只有在CLR调用静态构造函数时才会检查静态构造函数只运行一次,而不是在手动调用它时!:-)
| 归档时间: |
|
| 查看次数: |
283 次 |
| 最近记录: |