![](/img/trans.png)
[英]How to write overloaded generic extension methods for T[], T[][] without ambiguity?
[英]How to call overloaded methods having optional parameters without ambiguity for compiler?
我在 class 中有两个过载的 static function。 除了一个或两个参数之外,这两个重载都完全相同。 string body
是我的 function 中唯一必要的参数,你可以看到,rest 是可选参数。 但是参数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
}
现在,当我想从其他类中调用此 static function 时,由于string body
是唯一必需的参数,因此我有时会尝试编写:
ClassABC.Foo("hi there");
这给了我这个: The call is ambiguous between the following methods or properties
。 我知道为什么会发生这种情况,以及理想的解决方案是什么。 但我需要知道在 C# 中是否可以做任何其他事情来解决这个问题。
显然,编译器在选择 function 到 go 时感到困惑,但我不介意编译器会考虑两者在没有int x
和object y
的情况下是相同的。 基本上三个问题:
无论如何告诉编译器“采取任何”(几乎不可能的任务,但仍然让我知道)?
如果没有,无论如何我可以创建一个 function 来处理这两种情况吗? 像这样的东西:
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)
{
}
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)
{
}
编辑:既然你提到可能有 10 个左右的参数,你需要一个更通用的解决方案。
有一个带有变量 arguments 的选项。 检查每个参数的类型并采取相应措施:
public static void Foo(string body, param object[] the_rest_of_arguments)
{
}
如果两个 arguments 具有相同的类型但不同的功能(字符串标题,例如字符串作者),那么您需要其他东西。 您可以拥有一个 class,其中所有 arguments 作为成员。 用户应填写 class 的 object 并将 object 作为唯一参数传递:
public class FooArguments
{
public string caption;
public int x;
public object y;
}
public static void Foo(string body, FooArguments the_rest_of_arguments)
{
}
而不是 new class FooArguments 您可以使用Dictionary<string,object>
其中 key 是参数的名称,而 value 是参数本身。
如果 function 被不适当的 arguments 组合调用,那么只需抛出一个异常。
添加一个单独的重载来处理一个或两个 arguments 的情况。
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)
{
}
如果您需要处理 arguments 的任意组合,那么也许是时候将您的可选 arguments 分组到他们自己的 class 中了:
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)
{
}
提供一个包装器
公共 static void Foo(字符串主体)
{
public static void Foo(string body, "", null);
//leave it to me
}
或类似的东西
如何仅实现第二个变体并使用GetType()
检查作为第三个参数(如果有的话)传递的“对象”的实际类型? 然而,这假设跳过第三个参数( x = 0
或y = null
)将导致相同的结果。 请注意,这种方法提供的优化选项较少,因为选择必须在运行时进行 - 而不是编译时(除非编译器能够区分)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.