【发布时间】:2011-07-16 20:40:23
【问题描述】:
我在一个有两个重载的类中有一个静态函数。除了一个或两个参数之外,这两个重载都完全相同。 string body 是我的函数中您可以看到的唯一必要参数,其余是可选参数。但是参数object y 和int x 不应该放在一起。所以我不得不写两个重载如下。我提供一个示例代码:
public static void Foo(string body, string caption = "", int x = 0)
{
//leave it to me
}
public static void Foo(string body, string caption = "", object y = null)
{
//leave it to me
}
现在当我想从其他类调用这个静态函数时,由于string body是唯一需要的参数,我有时会尝试写:
ClassABC.Foo("hi there");
这给了我这个:The call is ambiguous between the following methods or properties。我知道为什么会发生这种情况,以及理想的解决方案是什么。但我需要知道是否可以在 C# 中做任何其他事情来解决这个问题。
显然,编译器在选择使用哪个函数时感到困惑,但我不介意编译器选择任何函数,因为没有int x 和object y 两者都是相同的。基本上三个问题:
有没有办法告诉编译器“接受任何”(几乎不可能完成的任务,但还是让我知道)?
-
如果没有,我是否可以创建一个函数来处理这两种情况?像这样的:
public static void Foo(string body, string caption = "", int x = 0 || object y = null) // the user should be able to pass only either of them! { //again, I can handle this no matter what } 还有其他解决方法吗?
编辑:
我无法重命名这两个函数。
我无法创建更多的重载。不仅仅是这些组合可能。我应该可以写
Foo(string body, int x)等。就这样。如果参数超过 10 个,则几乎不可能处理所有条件!总之,可选参数是必须的。
【问题讨论】:
标签: c# overloading optional-parameters argument-passing