C#-一个Action<>是否可能具有多个方法签名? [英] C# - Is it possible to have multiple method signatures for an Action<>?
问题描述
在C#中,是否可以有一个对象,该对象具有用于操作或委托的多个方法签名?像这样:
In C#, is it possible to have an object that has multiple method signatures for an Action<> or delegate? Like this:
class Foo
{
public Action<string> DoSomething;
public Action<string, string> DoSomething;
}
class Bar
{
public Bar()
{
Foo f1 = new Foo();
f1.DoSomething = (s) => { Console.Write(s) };
Foo f2 = new Foo();
f2.DoSomething = (s1, s2) => { Console.Write(s1 + s2) };
f1.DoSomething("Hi");
f2.DoSomething("Hi","World");
}
}
答案似乎是否定的,那是什么实施类似的正确方法? (这正试图解决的实际问题已通过另一种方式解决,这只是出于好奇)
The answer seems to be no, so what is the proper way to implement something like that? (The actual problem this was trying to solve has been solved a different way, this is just curiosity at this point)
推荐答案
A delegate
是单个方法的抽象(当然,多个具有相似签名的方法可以由一个委托代表,但从调用者的角度来看,它的行为就像单个方法一样,因此在这里是无关紧要的。)单个方法具有多个签名没有任何意义。因此,委托实例具有特定的签名。重载解析对委托没有任何意义。这不是您要选择的方法组。您直接指向一种方法并说调用此方法。
A delegate
is an abstraction of a single method (of course, several methods with similar signatures can be represented by a single delegate but from the caller's perspective, it behaves just like a single method, so that's irrelevant here.) It doesn't make sense for a single method to have multiple signatures. Hence, a delegate instance has a specific signature. Overload resolution does not have any meaning for delegates. It's not a method group you're choosing from. You're directly pointing to a method and saying "call this."
此问题的解决方案是什么?
What's the solution to this problem?
我不清楚实际的问题是什么。
It's not clear to me what the actual problem is. This might be what you're looking for:
class Foo {
public Action<string> DoSomethingDelegate1;
public Action<string,string> DoSomethingDelegate2;
public void DoSomething(string s) { DoSomethingDelegate1(s); }
public void DoSomething(string s, string t) { DoSomethingDelegate2(s, t); }
}
class Bar
{
public Bar()
{
Foo f1 = new Foo();
f1.DoSomethingDelegate1 = (s) => { Console.Write(s) };
Foo f2 = new Foo();
f2.DoSomethingDelegate2 = (s1, s2) => { Console.Write(s1 + s2) };
f1.DoSomething("Hi");
f2.DoSomething("Hi","World");
}
}
这篇关于C#-一个Action<>是否可能具有多个方法签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!