问题描述
我正在使用以下方法:
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 中,Predicate<T> 等就是很好的例子,但是你必须有相同数量的 args.在这种情况下,也许一种选择是使用捕获将 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);
}
请注意,Action 是在 .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
注意匿名方法(delegate {...})也可以参数化:
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 使用lambdas"让这一切变得更容易和更漂亮,但这是另一个话题;-p
Finally, C# 3.0 makes this all a lot easier and prettier with "lambdas", but that is another topic ;-p
这篇关于具有不同参数的两个方法的 C# 委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)