c# – 无论如何都可以创建一个公共静态构造函数吗?
在Visual Studio 2012中有一条规则说:
Static constructors should be private,但编译器不允许这样做.所以无论如何我们可以创建公共静态构造函数吗?
更新:在链接中,它说“如果静态构造函数不是私有的,它可以由系统以外的代码调用.”它让我想到了这个问题. 解决方法
您必须省略public / private修饰符:
public class Test { static Test() { } } 实际上,私有静态构造函数的概念有点脆弱,因为静态构造函数只能由CLR(运行时)调用(并且可以调用).因此私有存在可能只是因为每个方法都必须有一个修饰符,而不是因为它意味着任何东西(说清楚:私有非静态构造函数可以由定义它的类调用,而静态构造函数不能由定义它的类直接调用) 请注意,从技术上讲,通过直接编写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); } } 使用Visual Studio编译它. 从开发人员命令提示符: ildasm YourExe.exe /out:test.il 将主体更改为 .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 然后将Test.cctor签名更改为 .method public hidebysig specialname rtspecialname static (见公众?) 现在 ilasm test.il test.exe 输出: Static constructor: IsPublic: True,IsPrivate: False Static constructor: IsPublic: True,IsPrivate: False 静态构造函数已执行两次:您对.cctor的调用以及CLR对.cctor执行的自动调用.只有在CLR调用静态构造函数时才会检查静态构造函数只运行一次,而不是在手动调用它时! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |