1

所以在过去的一个小时里,我一直在尝试使用 VB.NET 中的动态方法来调用调用类中的子类。

我有几件事没有运气。首先,在尝试遵循 MSDN (http://msdn.microsoft.com/en-us/library/ms228971.aspx) 中的示例时,我无法将该方法设为 Sub 并且根本不返回任何内容,因为我只想调用另一个方法。

例如。

Private Sub FirstMethod()

    Dim methodArgs As Type() = {}
    Dim MyNewMethod As New DynamicMethod("MyNewMethod", Nothing, methodArgs, GetType(Crux).Module)
    Dim il As ILGenerator = MyNewMethod.GetILGenerator()
    il.Emit(OpCodes.Call, OtherMethod)
    il.Emit(OpCodes.Ret)
End Sub

Private Sub OtherMethod()
    MsgBox("This is some other method!")
End Sub

问题是,我不希望它返回任何东西,我只希望它调用 OtherMethod() 并且我想要一种在我的代码中调用动态方法的方法(通过委托)。MSDN 根本没有真正的帮助,我找不到任何东西甚至试图解释一种方法来做我想做的事。

任何帮助是极大的赞赏。

4

2 回答 2

1

为什么不尝试使用 linq 表达式并将它们编译成委托。它比旧时尚的反射更容易。发射。

  class Demo {
    public void Foo() {
        var instance = new Demo();
        var method = Expression.Call(Expression.Constant(instance), instance.GetType().GetMethod("Bar"));
        var del = Expression.Lambda(method).Compile();
        del.DynamicInvoke();
    }

    public void Bar() {
        Console.WriteLine("Bar");
    }
}
于 2012-05-07T21:25:45.600 回答
0

ADynamicMethod并不是真正关于动态调用方法,而是关于动态构建方法,就像在运行时构建完整的方法体一样。

如果你想调用一个方法,你可以简单地使用你已经拥有的Invoke方法。MethodInfo其中,对于没有参数的 void 方法很简单

var type = this.GetType();
var method = type.GetMethod("OtherMethod");
...
method.Invoke(this, null); // call this.OtherMethod()

现在,如果你想将它封装在 a 中Delegate,你可以使用

var action = (Action) Delegate.CreateDelegate(typeof(Action), this, "OtherMethod");

action(); // call this.OtherMethod()

我在这里选择了 Action 作为委托的类型,但您可以使用任何兼容的委托类型。

这里有几个重载Delegate.CreateDelegate可以帮助您,包括采用 a 的重载MethodInfo,因此您可以使用反射来获取正确的方法信息,以及调用CreateDelegate您想要的类型的委托。


请注意,如果您要调用的方法在编译时已知,则可以跳过整个反射,让编译器为您完成工作:

Action action = this.OtherMethod; // using a so-called method group
Action action = () => this.OtherMethod(); // using a lambda
Action action = delegate { this.OtherMethod(); } // using an anonymous method
于 2012-05-07T22:16:45.293 回答