动态分配方法/方法作为变量 [英] Dynamically assign method / Method as variable

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

问题描述

所以我有两个名为A和B的类.

So i have 2 classes named A and B.

A有一个方法"public void Foo()".

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

B还有其他几种方法.

B has several other methods.

我需要的是类B中的一个变量,该变量将被分配为类A的Foo()方法. 此后,该变量应执行"(=>,因此应执行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).

该怎么做?

推荐答案

里德给了您正确的答案.还值得指出的是,除了Action之外,您还可以使用其他委托签名.

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

有通用版本,例如Action<T>(一个arg),Action<T1, T2>(两个args)等. 另外,如果您的方法具有返回类型,请检出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.

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

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