我遇到了一个问题,其中一个类的静态构造函数在它应该被调用之前被调用.(即,DI/IoC未设置,它从服务定位器返回null/exception).
遗憾的是,我对静态构造函数没有很多控制权,不要问我为什么要依赖DI/IoC进行设置,但确实如此.
在我的应用程序中,在我的IoC准备就绪之前,没有任何东西应该引用此类静态或其他方式,但静态构造函数仍在执行.
有没有一种简单的方法来确定导致构造函数执行的行?注意:我无法断点,static constructor因为这是在ASP.NET的远程调试器可以附加到Web服务器之前发生的(在Global.asax.cs中)
考虑:
class Foo
{
static Foo()
{
// Static initialisation
}
}
Run Code Online (Sandbox Code Playgroud)
为什么()需要static Foo() {...}?静态构造函数必须始终是无参数的,为什么要这么麻烦?它们是否有必要避免一些解析器歧义,或者只是为了保持与常规无参数构造函数的一致性?
由于它看起来非常像初始化块,我经常发现自己意外地将它们排除在外,然后不得不考虑几秒钟的错误.如果他们可以以同样的方式被淘汰将是很好的.
在我的类我有一个字符串对象的静态字典,其中包含大量的项目(它从一个文件读取并初始化它们)我写了一个静态构造函数,这需要几秒钟,但我想做一次为了更快,因为我在ASP.Net中这样做,我希望我的网站不要有这个开销,我该怎么办?如果这个构造函数为每个对象运行,那么我正在考虑一些方法,但我想我必须在用户运行的网站的每个页面中运行此方法,所以我想再次它会是相同的,我是对的吗?什么是初始化一大组变量的解决方案?谢谢
请考虑以下示例情况:
public abstract class Parent
{
private ByteBuffer buffer;
/* Some default method implementations, interacting with buffer */
public static Parent allocate(int len)
{
// I want to provide a default implementation of this -- something like:
Parent p = new Parent();
p.buffer = ByteBuffer.allocate(len);
return p;
}
}
public class Child extends Parent
{
/* ... */
}
public class App
{
public static void main(String[] args)
{
// I want to ultimately do something like:
Child c = …Run Code Online (Sandbox Code Playgroud) 只是一个简单的观察.该属性MethodBase.IsConstructor不适用于static构造函数,并且文档没有提到这个事实(引用:" 如果此方法是由对象表示的构造函数,则为trueConstructorInfo ").
样品:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
问题:为什么?错误或不完整的规范?
从MSDN
静态构造函数用于初始化任何静态数据,或执行仅需要执行一次的特定操作。在创建第一个实例或引用任何静态成员之前,它将自动调用
现在出现了我的问题:
public static class DateFormat
{
private static List<string> DateFormats = new List<string>();
public static string DateSeparator { get; set; } = "/";
public static string Current { get; set; } = DateFormats[1]; // error here
static DateFormat()
{
DateFormats.Add("yyyy{0}MM{0}dd HH{1}mm{1}ss");
DateFormats.Add("yyyy{0}MM{0}dd hh{1}mm{1}ss");
}
}
Run Code Online (Sandbox Code Playgroud)
如您在调用DateFormats[1]错误时看到的
“'DateFormat'的类型初始值设定项引发了异常。”
构造函数应该先调用静态构造函数吗?这样该字典将被填充,然后任何使用它的对变量的调用都可以。
我的一个类有一个相当大的静态构造函数,并且想要重构它以将初始化的各个部分封装在静态函数中。
One of the things this static constructor does a lot of is initialize the values of static readonly fields. However, when I try to move these parts into functions, obviously the compiler wont let me as these can only be set in the static constructor. This makes sense as it doesn't know that I only intend to call these functions from my static constructor.
Is there any way around this? e.g. is there some sort of attribute I can …
c# ×6
.net ×3
constructor ×2
asp.net ×1
debugging ×1
dictionary ×1
java ×1
reflection ×1
static ×1