C#委托两种方式使用不同的参数

编程入门 行业动态 更新时间:2024-10-25 16:26:06
本文介绍了C#委托两种方式使用不同的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用下面的方法:

public void M1(Int32 a) { // acquire MyMutex DoSomething(a); // release MyMutex }

public void M2(String s, String t) { // acquire MyMutex DoSomethingElse(s, t); // release MyMutex }

这是我迄今发现。似乎是不可能使用一个单一的委托两种方法具有不同的签名

From what I have found so far it seems that it is not possible to use a single delegate for two methods with different signatures.

还有没有其他办法来写这样的事:

Are there any other alternatives to write something like this:

public void UsingMutex(...) { // acquire MyMutex ... // release MyMutex } UsingMutex(M1); UsingMutex(M2);

所有我能想到的那一刻是使用两个代表和一个布尔标志知道哪个委托打电话,但它不是一个长期的解决方案。

All I can think for the moment is to use two delegates and a boolean flag to know which delegate to call, but it is not a long term solution.

这是可能的仿制药与代表结合? ?如果是的话,你有任何类型的文档中的某些环节

It is possible to combine generics with delegates? And if so, do you have some links for any kind of documentation?

环境:C#2.0

推荐答案

当然你可以混合使用泛型代表。在2.0中,谓词< T> 等就是很好的例子,但你必须有相同数量的参数的个数。在这种情况下,也许是一个选择是使用捕捉包括在委托ARGS?

Absolutely you can mix delegates with generics. In 2.0, Predicate<T> etc are good examples of this, but you must have the same number of args. In this scenario, perhaps an option is to use captures to include the args in the delegate?

public delegate void Action(); static void Main() { DoStuff(delegate {Foo(5);}); DoStuff(delegate {Bar("abc","def");}); } static void DoStuff(Action action) { action(); } static void Foo(int i) { Console.WriteLine(i); } static void Bar(string s, string t) { Console.WriteLine(s+t); }

注意动作为你的定义是在.NET 3.5,但你可以重新声明它为2.0目的;-p

Note that Action is defined for you in .NET 3.5, but you can re-declare it for 2.0 purposes ;-p

请注意,该匿名方法(委托{...} )也可参数化:

Note that the anonymous method (delegate {...}) can also be parameterised:

static void Main() { DoStuff(delegate (string s) {Foo(5);}); DoStuff(delegate (string s) {Bar(s,"def");}); } static void DoStuff(Action<string> action) { action("abc"); } static void Foo(int i) { Console.WriteLine(i); } static void Bar(string s, string t) { Console.WriteLine(s+t); }

最后,C#3.0,使这一切更容易和漂亮与lambda表达式 ,但那是另一个话题;-p

Finally, C# 3.0 makes this all a lot easier and prettier with "lambdas", but that is another topic ;-p

更多推荐

C#委托两种方式使用不同的参数

本文发布于:2023-10-26 21:53:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531453.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两种   参数   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!