显式调用静态构造函数

时间:2012-07-17 10:42:06

标签: c# mstest system.reflection static-constructor

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

调用静态构造函数时
Manager_Accessor.name = "Test"
typeof(Manager).TypeInitializer.Invoke(null, null); 

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

public class Manager
{        
        private static string name= "MyEntity";

        private static object mgr;

        static Manager()
        {
            try
            {
                mgr = CreateMgr(name);
            }
            catch (Exception ex)
            {
                mgr=null;
            }
        }
}

5 个答案:

答案 0 :(得分:36)

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

来自another Stackoverflow post

  

其他答案非常好,但如果你需要强迫上课   构造函数在没有引用类型的情况下运行(即。   反思),你可以使用:

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

我必须将此代码添加到我的应用程序to work around a possible bug in the .net 4.0 CLR

答案 1 :(得分:4)

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

只需访问要调用其静态构造函数的类。 E.g:

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;
}

答案 2 :(得分:3)

对于任何找到这个帖子并且想知道的人......我刚刚做了测试。看来System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor()只会运行静态构造函数,如果已经因其他原因而被运行。

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

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

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

只需将 public static void Initialize(){} 方法添加到您的静态类中,然后在需要时调用它即可。这与调用构造函数非常相似,因为将自动调用静态构造函数。