显式调用静态构造函数 [英] Explicitly call static constructor

查看:207
本文介绍了显式调用静态构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要写单元测试下面的类。

。如果名字是不是myEntity所等那么经理应该是空白。

否定单元测试

使用Manager专用访问我要改名字为测试,让经理应为空。
,然后将验证经理的价值。
。要做到这一点,我想明确地调用静态构造函数
,但是当我打电话使用



静态构造函数

  Manager_Accessor.name =测试
的typeof(经理).TypeInitializer.Invoke(NULL,NULL);



名字总是设置为myEntity所如何设置名称为测试并调用静态构造函数

 公共类经理
{
私有静态字符串名称=myEntity所;

私人静态对象经理;

静态管理器()
{

{
经理= CreateMgr(名);
}
赶上(异常前)
{
经理= NULL;
}
}
}


解决方案

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



从的另一个岗位#1




其他答案是优秀的,但如果你需要强制的一类
构造函数,而无需一个参考类型运行,您可以使用(即
反射):

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




我不得不将此代码添加到我的应用程序的to工作围绕在.NET 4.0 CLR 一个可能的错误。


I want to write unit test for below class.
If name is other than "MyEntity" then mgr should be blank.
Negative Unit test
Using Manager private accessor I want to change name to "Test" so that mgr should be null. And then will verify the mgr value. To achieve this, I want to explicitly call the static constructor but when I call the static constructor using

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

name is always set to "MyEntity" how to set name to "Test" and invoke the static constructor.

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

        private static object mgr;

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

解决方案

As I found out today, the static constructor CAN be called directly:

from another Stackoverflow post

The other answers are excellent, but if you need to force a class constructor to run without having a reference to the type (ie. reflection), you can use:

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

I had to add this code to my application to work around a possible bug in the .net 4.0 CLR.

这篇关于显式调用静态构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆