【问题标题】:C# calling a public non-static method using reflection without instantiating its classC# 使用反射调用公共非静态方法而不实例化其类
【发布时间】:2011-06-17 14:10:44
【问题描述】:

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

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

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

检测到致命的执行引擎错误: 运行时遇到致命错误。错误地址位于线程 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());
        }

谢谢

【问题讨论】:

  • public static void MyMethod() 这不是非静态的。 NO 你不能在不创建实例的情况下调用非静态方法。
  • 您的意思是让MyMethod 静态化吗?
  • 只是出于好奇——您希望实现什么目标?
  • 你为什么要这样做?
  • @Bala 我删除了 static 关键字,我的错误:(

标签: c# reflection dynamicmethod


【解决方案1】:

我不知道。因为它不是静态的。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 2011-08-03
    相关资源
    最近更新 更多