C#接口重载实现

Jus*_*ahn 2 c# overloading interface

我有一个重载方法的接口.

interface ISide
{
    Dictionary<string, decimal> Side(string side1, decimal cost1);
    Dictionary<string, decimal> Side(string side1, decimal cost1, string side2, decimal cost2);
}
Run Code Online (Sandbox Code Playgroud)

我想只实现其中一个,具体取决于哪个类继承它,但我通过尝试每个类只实现其中一个方法来获得编译器错误.

class Entree: ISide
{
    public Dictionary<string, decimal> Side(string side1, decimal cost1, string side2, decimal cost2);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我是否必须使用可选参数来实现我在这里尝试做的事情?

Yau*_*sau 6

interface ISomething1
{
    int SomeMethod(int someInt1);
    }

interface ISomething2
{
    int SomeMethod(int someInt1, int someInt2);
}

class Someclass1 : ISomething1
{
    public int SomeMethod(int someInt1);
}

class Someclass2 : ISomething2
{
    int SomeMethod(int someInt1, int someInt2);
}

class Someclass3 : ISomething1, ISomething2 
{
    public int SomeMethod(int someInt1);
    int SomeMethod(int someInt1, int someInt2);
}
Run Code Online (Sandbox Code Playgroud)


Sel*_*enç 5

你不能那样做。你必须实现你的接口中定义的所有方法。但是params如果只有你的参数计数改变,你可以使用关键字。

interface ISomething
{
    int SomeMethod(params int[] numbers);
}
Run Code Online (Sandbox Code Playgroud)

如果您想至少需要一个参数,那么您可以执行以下操作:

 int SomeMethod(int x, params int[] numbers);
Run Code Online (Sandbox Code Playgroud)


Cal*_*leb 5

你应该把概念 string side1, decimal cost1变成一个对象.

public class MenuItem
{
    public string Name {get; set;}
    public decimal Cost {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

然后你的界面列出了一个 MenuItem

interface ISide
{
    Dictionary<string, decimal> Side(IEnumberable<MenuItem> sides);
}
Run Code Online (Sandbox Code Playgroud)

现在,这就是说.这似乎不可思议,我认为EntreeISide.您应该尝试更具体地说明该接口的含义(可能IComeWithSides或某事)

  • 然后您的接口应该将集合对象作为参数. (2认同)
  • 我倾向于同意,尽管如果OP提供更多关于上下文的细节会容易得多。很难对“ISomething”提供好的建议:p (2认同)
  • 但是,当您提供更多背景信息时,“问题”的解决方案就完全改变了。原来的答案完全不相关,因为我们不知道上下文。 (2认同)