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)
在这种情况下,我是否必须使用可选参数来实现我在这里尝试做的事情?
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)
你不能那样做。你必须实现你的接口中定义的所有方法。但是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)
你应该把概念 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)
现在,这就是说.这似乎不可思议,我认为Entree是ISide.您应该尝试更具体地说明该接口的含义(可能IComeWithSides或某事)
| 归档时间: |
|
| 查看次数: |
7195 次 |
| 最近记录: |