本文介绍了我如何调用与反思的静态构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能获得 ConstructorInfo 的静态构造函数?

 公共类MyClass的
{
    公共静态INT someValue中;    静态MyClass的()
    {
        someValue中= 23;
    }
}

我试过下面的失败....

  MyClass类型= ty​​peof运算(MyClass的); //抛出异常
 myClass.TypeInitializer.Invoke(NULL); //返回null(也尝试删除BindingFlags.Public
 ConstructorInfo CI = myClass.GetConstructor(BindingFlags.Static | BindingFlags.Public,System.Type.DefaultBinder,System.Type.EmptyTypes,NULL); //返回空数组
 ConstructorInfo [] = clutchingAtStraws myClass.GetConstructors(BindingFlags.Static | BindingFlags.Public);


解决方案

使用 myClass.TypeInitializer.Invoke(NULL,NULL)

我只是尝试这样做,它工作得很好。

我强烈建议你的的做到这一点,但是 - 它违反了一种期待静态构造函数只执行一次。

How can I get the ConstructorInfo for a static constructor?

public class MyClass
{
    public static int SomeValue;

    static MyClass()
    {
        SomeValue = 23;
    }
}

I've tried the following and failed....

 Type myClass = typeof (MyClass);

 // throws exception
 myClass.TypeInitializer.Invoke(null);

 // returns null (also tried deleting  BindingFlags.Public
 ConstructorInfo ci = myClass.GetConstructor(BindingFlags.Static|BindingFlags.Public, System.Type.DefaultBinder, System.Type.EmptyTypes, null);

 // returns empty array
 ConstructorInfo[] clutchingAtStraws = myClass.GetConstructors(BindingFlags.Static| BindingFlags.Public);
解决方案

Use myClass.TypeInitializer.Invoke(null, null).

I've just tried this and it worked fine.

I would strongly recommend that you don't do this, however - it violates a type expecting the static constructor to only be executed once.

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

06-28 15:20