- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在一个有两个重载的类中有一个静态函数。除了一个或两个参数外,这两种重载都完全相同。 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 个,则几乎不可能处理所有情况。总之,可选参数是必须的。
最佳答案
添加一个单独的重载来处理带有一个或两个参数的情况。
public static void Foo(string body, string caption = "")
{
}
public static void Foo(string body, string caption, int x)
{
}
public static void Foo(string body, string caption, object y)
{
}
如果您需要处理参数的任意组合,那么也许是时候将您的可选参数分组到它们自己的类中了:
public sealed class Options
{
public string Caption { get; set; }
public int X { get; set; }
public object Y { get; set; }
}
public static void Foo(string body, Options options)
{
}
关于c# - 如何在没有歧义的情况下调用具有可选参数的重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6720098/
我是一名优秀的程序员,十分优秀!