0

是否可以在 C# 中调用方法(非静态)而不实例化其类,例如:

public class MyClass
{
    public void MyMethod()
    {
        Console.WriteLine("method called");
    }
}

我已经使用 System.Reflection.Emit 命名空间尝试了这种方法,我将 MyMethod() 的 IL 复制到了动态方法中,但出现了异常:

检测到 FatalExecutionEngineError :运行时遇到致命错误。错误地址位于线程 0x2650 上的 0x5dceccf5。错误代码为 0xc0000005。此错误可能是 CLR 中的错​​误或用户代码的不安全或不可验证部分中的错误。此错误的常见来源包括 COM 互操作或 PInvoke 的用户封送错误,这可能会损坏堆栈。

        Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
        Type t = a.GetType("Tutorial.MyClass");
        MethodInfo m = t.GetMethod("MyMethod");
        MethodBody mb = m.GetMethodBody();

        DynamicMethod dm = new DynamicMethod("MethodAlias", null, Type.EmptyTypes, typeof(Tutorial.MainWindow), true);
        DynamicILInfo ilInfo = dm.GetDynamicILInfo();
        SignatureHelper sig = SignatureHelper.GetLocalVarSigHelper();
        ilInfo.SetLocalSignature(sig.GetSignature());
        ilInfo.SetCode(mb.GetILAsByteArray(), mb.MaxStackSize);

        try
        {
            dm.Invoke(this, null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

谢谢

4

1 回答 1

3

从来没听说过。因为它不是静态的。

我只会说“不”,但我的回答还不够长。

于 2011-06-17T14:12:25.320 回答