问题描述
首先,我阅读了一些论坛和 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:我希望拥有任意数量的 OneDelegate 声明,而不仅仅是一两个.
PS1: I want to have any number of OneDelegate declarations, not just one or two.
推荐答案
想象一下这是可能的.假设我可以有一个重载的委托:
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
传递给其他代码,该代码执行以下操作:
Now you pass myDelegate
to some other code, and that code does this:
myDelegate(47);
您希望在这种情况下会发生什么?运行时如何调用带有整数参数的StringMethod()
?
What do you expect to happen in this case? How can the runtime call StringMethod()
with an integer argument?
如果你真的想要一个可以接受任何参数集的委托,那么唯一的选择就是有一个带有 params object[]
数组的委托:
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.");
}
如您所见,这很快就会变得一团糟.因此,我向您提出,如果您需要这样的代表,您可能在建筑设计的某个地方犯了错误.在继续实施之前识别此缺陷并修复设计,否则代码的可维护性将受到影响.
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# - 我怎样才能“重载"?代表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!