显式调用静态构造函数

我想为下面的课程编写unit testing。
如果名称不是“MyEntity”,则mgr应为空白。
负unit testing
使用Manager私有访问器我想将名称更改为“Test”,以便mgr应为null。 然后将validationmgr值。 为了实现这一点,我想显式调用静态构造函数,但是当我使用静态构造函数调用时

Manager_Accessor.name = "Test" typeof(Manager).TypeInitializer.Invoke(null, null); 

name始终设置为“MyEntity”如何将名称设置为“Test”并调用静态构造函数。

 public class Manager { private static string name= "MyEntity"; private static object mgr; static Manager() { try { mgr = CreateMgr(name); } catch (Exception ex) { mgr=null; } } } 

正如我今天发现的那样,可以直接调用静态构造函数:

来自另一个Stackoverflowpost

其他答案非常好,但是如果你需要强制一个类构造函数运行而不需要引用类型(即reflection),你可以使用:

 Type type = ...; System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle); 

我不得不将此代码添加到我的应用程序中以解决.net 4.0 CLR中可能存在的错误 。

如果你的类中有一个静态成员(必须有,否则静态构造函数不会做太多),那么就不需要显式调用静态构造函数。

只需访问要调用其静态构造函数的类。 例如:

 public void MainMethod() { // Here you would like to call the static constructor // The first access to the class forces the static constructor to be called. object temp1 = MyStaticClass.AnyField; // or object temp2 = MyClass.AnyStaticField; } 

对于任何人发现这个线程并想知道…我刚刚做了测试。 看来System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor()只会运行静态构造函数(如果由于其他原因尚未运行)。

例如,如果您的代码不是肯定的,无论先前的代码是否已经访问过该类并触发了静态构造函数的运行,那都没关系。 之前的访问将触发静态构造函数运行,但RunClassConstructor()也不会运行它。 RunClassConstructor()仅运行静态构造函数(如果尚未运行)。

在RunClassConstructor()之后访问类也不会导致静态构造函数再次运行。

这是基于Win10 UWP应用程序中的测试。

将您要在构造函数中调用的代码放入公共方法并从构造函数中调用它