我正在使用反射类调用其他dll上的一些方法。其中一个方法的参数是委托类型。
我希望通过反射来调用这些方法。所以我需要将函数参数作为对象数组传递,但我找不到任何关于如何将委托转换为对象的内容。
提前致谢。
我希望通过反射来调用这些方法。所以我需要将函数参数作为对象数组传递,但我找不到任何关于如何将委托转换为对象的内容。
提前致谢。
代理是一个对象。只需像通常创建预期的代理一样,并将其传递给参数数组即可。这里有一个相当牵强的例子:
class Mathematician {
public delegate int MathMethod(int a, int b);
public int DoMaths(int a, int b, MathMethod mathMethod) {
return mathMethod(a, b);
}
}
[Test]
public void Test() {
var math = new Mathematician();
Mathematician.MathMethod addition = (a, b) => a + b;
var method = typeof(Mathematician).GetMethod("DoMaths");
var result = method.Invoke(math, new object[] { 1, 2, addition });
Assert.AreEqual(3, result);
}
Predicate<int> p = (i)=> i >= 42;
Object[] arrayOfObject = new object[] { p };
class Program
{
public delegate void TestDel();
public static void ToInvoke(TestDel testDel)
{
testDel();
}
public static void Test()
{
Console.WriteLine("hello world");
}
static void Main(string[] args)
{
TestDel testDel = Program.Test;
typeof(Program).InvokeMember(
"ToInvoke",
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
null,
null,
new object[] { testDel });
}
}
你可以将委托看作是变量类型“函数”。委托描述了匹配函数的参数和返回值。
delegate void Foo(int a); // here a new delegate obj type Foo has been declared
上面的例子允许使用“Foo”作为数据类型,唯一允许与类型为Foo数据类型的变量匹配的对象是具有相同签名的方法,因此:
void MyFunction(int x);
Foo D = MyFunction; // this is OK
void MyOtherFunction(string x);
Foo D = MyOtherFunction; // will yield an error since not same signature.
int n = 1;
D( n ); // or D.Invoke( n );