繁体   English   中英

C#使用反射调用公共非静态方法而不实例化其类

[英]C# calling a public non-static method using reflection without instantiating its class

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

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

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

检测到FatalExecutionEngineError:运行时遇到致命错误。 错误的地址位于线程0x2650上的0x5dceccf5。 错误代码为0xc0000005。 此错误可能是CLR或用户代码中不安全或不可验证部分的错误。 该错误的常见来源包括COM-interop或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());
        }

谢谢

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM