C#中:动态分配方法/方法的变量 [英] C#: Dynamically assign method / Method as variable

查看:233
本文介绍了C#中:动态分配方法/方法的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有2个班命名为A和B。

So i have 2 classes named A and B.

一个有一个方法公共无效美孚()。

A has a method "public void Foo()".

b有其他的几种方法。

B has several other methods.

我需要的是b类的变量,将分配类A $的美孚()方法b $ b该变量应该事后被执行(=>所以应该执行A级分配的方法)。

What i need is a variable in class B, that will be assigned the Foo() method of class A. This variable should afterwards be "executed" (=> so it should execute the assigned method of class A).

如何做到这一点?

推荐答案

里德给你正确的答案。另外值得指出的是,你可以用其他代表签名行动之外。

Reed gave you the right answer. It's also worth pointing out that you can use other delegate signatures besides Action.

有仿制药,比如动作< T> (一个ARG),动作< T1,T2> (二参数)等...
此外,如果你的方法有一个返回类型,检查 Func键< T,TResult>

There are generic versions like Action<T> (one arg), Action<T1, T2> (two args), etc... Also if your method has a return type, check out Func<T, TResult>.

  • Action docs: http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
  • Func docs: http://msdn.microsoft.com/en-us/library/bb549151.aspx

或者你当然可以定义自己的委托类型。

Or of course you can define your own delegate type.

这篇关于C#中:动态分配方法/方法的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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