C# - 我怎么能和QUOT;超载"委托? [英] C# - How can I "overload" a delegate?
问题描述
首先,我读了一些论坛和MSDN的帮助和所有说的委托,不能超载。
First, I was reading some forums and the help in MSDN and all says that a delegate can't be overloaded.
现在,我想有这样的事情:
Now, I want to have something like this:
public delegate void OneDelegate();
public delegate void OneDelegate(params object[] a);
public void DoNothing(params object[] a) {}
public void DoSomething() { /* do something */ }
private OneDelegate someFunction;
someFunction = new OneDelegate(DoSomething);
someFunction = new OneDelegate(DoNothing);
所以,就像你知道,你不能这样做,因为OneDelegate仅指第一个,而不是第二个。但是,有没有这样做的方法吗?或者类似的东西?
So, like you know, you CAN'T do this, because OneDelegate only refers to the first one and not the second one. But, is there a way for doing this? or something like that?
PS1:我wan't有任何数量的OneDelegate声明的,不只是一个或两个结果。
PS2:对不起,我英文不好
PS1: I wan't to have any number of OneDelegate declarations, not just one or two.
PS2: Sorry for my bad English.
推荐答案
设想一下,这是可能的。想我可以有一个重载的代表:
Imagine for a moment this was possible. Suppose I could have an overloaded delegate:
public delegate void OneDelegate(int i);
public delegate void OneDelegate(string s);
现在想象我宣布这个类型的变量,然后分配给它的功能,例如:
Now imagine I declare a variable of this type and then assign a function to it, for example:
OneDelegate myDelegate = StringMethod;
其中, StringMethod
的正是如此宣称:
public void StringMethod(string s) { Console.WriteLine(s); }
现在你通过 myDelegate
其他一些code,而code做到这一点:
Now you pass myDelegate
to some other code, and that code does this:
myDelegate(47);
你有什么期望在这种情况下发生?怎样才能运行调用 StringMethod()
与整数参数?
如果你真的想要一个代表,可以采取的任何一组参数,在所有的,那么唯一的选择是有一个具有 params对象[]
数组:
If you really want a delegate that can take any set of parameters at all, then the only option is to have one with a params object[]
array:
public delegate void OneDelegate(params object[] parameters);
但你必须分配给它,实际上可以处理任何对象数组的函数,例如:
But then you will have to assign to it a function that can actually handle any object array, for example:
public void MyMethod(params object[] parameters)
{
if (parameters == null || parameters.Length == 0)
throw new ArgumentException("No parameters specified.");
if (parameters.Length > 1)
throw new ArgumentException("Too many parameters specified.");
if (parameters[0] is int)
IntMethod((int) parameters[0]);
else if (parameters[0] is string)
StringMethod((string) parameters[0]);
else
throw new ArgumentException("Unsupported parameter type.");
}
如你所见,这变得混乱真正的快。因此,我向你,如果你需要这样一个代表,你可能已经在某个地方你的建筑设计犯了一个错误。确定这一缺陷,你着手实施之前,否则你的code的可维护性将遭受修复设计。
As you can see, this gets messy real quick. Therefore, I submit to you that if you need such a delegate, you have probably made a mistake somewhere in your architectural design. Identify this flaw and fix the design before you proceed with the implementation, as otherwise the maintainability of your code will suffer.
这篇关于C# - 我怎么能和QUOT;超载"委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!