简体   繁体   中英

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

Is-it possible in C# to call a method (non-static) without instantiating its class eg :

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

I've tried this method using the System.Reflection.Emit namespace, I copied the IL of MyMethod() to a dynamic method but got an exception :

FatalExecutionEngineError was detected : The runtime has encountered a fatal error. The address of the error was at 0x5dceccf5, on thread 0x2650. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

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

Thank you

Not that I know of. Because it's not static.

I would just say "No" but my reply wasn't long enough for SO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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