Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

generics - C# delegate for two methods with different parameters

I am using the following methods:

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

and

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?

Environment: C# 2.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

i.e.

    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);
    }

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);
    }

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...