如何转换委托在C#中的对象? [英] How to convert delegate to object in C#?

查看:163
本文介绍了如何转换委托在C#中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用反射类调用一些方法这是对其他一些DLL。
和方法参数之一是委托类型。

I am using reflection class to invoke some methods which are on the some other dll. And one of the methods' parameters are type of delegate.

和我想调用该方法,通过使用反射。
所以我需要传递函数的参数为​​对象数组,但我无法找到
如何委托对象转换任何东西。

And I want to invoke this methods by using reflection. So I need to pass function parameters as object array, but I could not find anything about how to convert delegate to object.

谢谢提前

推荐答案

委托是一个对象。只要创建了预期的委托,你通常会,并把它传递的参数数组中为止。这是一个虚构的例子:

A delegate is an object. Just create the expected delegate as you would normally, and pass it in the parameters array. Here is a rather contrived example:

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

这篇关于如何转换委托在C#中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆