问题描述
我正在使用以下方法:
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# 委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!