C#委托两种方式使用不同的参数 [英] C# delegate for two methods with different parameters

查看:891
本文介绍了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#委托两种方式使用不同的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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