C#中:动态分配方法/方法的变量 [英] C#: Dynamically assign method / Method as variable
问题描述
所以,我有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> $ 。C $ C>
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>
.
- 操作文档:的 http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
- Func键文档:<一HREF =http://msdn.microsoft.com/en-us/library/bb549151.aspx相对=nofollow> http://msdn.microsoft.com/en-us/library/bb549151.aspx 一>
- 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屋!