gpt4 book ai didi

c# - 如何在没有歧义的情况下调用具有可选参数的重载方法?

转载 作者:行者123 更新时间:2023-11-30 13:28:13 29 4
gpt4 key购买 nike

我在一个有两个重载的类中有一个静态函数。除了一个或两个参数外,这两种重载都完全相同。 string body是我的函数中唯一必要的参数,你可以看到,其余的是可选参数。但是参数object yint 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 .基本上三个问题:

  1. 有没有办法告诉编译器“接受任何”(几乎不可能完成的任务,但仍然让我知道)?

  2. 如果没有,我是否可以创建一个函数来处理这两种情况?像这样:

    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
    }
  3. 还有其他解决方法吗?

编辑:

  1. 我无法重命名这两个函数。

  2. 我无法创建更多重载。不仅仅是这些组合成为可能。我应该可以写 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com