c# - 在 C# 中定义具有不同参数的接口(interface)方法

标签 c# interface

interface parentInterface
{
   public String methodA(/*define parameters name and dataType*/);
}

public class childA : parentInterface
{
  public String methodA(String a, int b, String c, long d){}
}

public class childB : parentInterface
{
   public String methodA(int e, String f, String g){}
}

我想定义接口(interface)方法的参数名称和数据类型

最佳答案

创建新参数

这通常可以通过使用 classstruct 作为单个参数而不是内置类型来解决。

界面

class 实现熟悉的 interface 时,您知道该期待什么。我们知道所有实现IEnumerable接口(interface)的类都可以在foreach循环中使用。按照惯例,接口(interface)的名称是“I”,后跟对能力的描述。名称通常以后缀“-able”结尾。

-able   Suffix forming adjectives meaning:
           1   -able to be [as in] calculable.
           2   -having the quality of [as in] comfortable.

Oxford English Dictionary

让我们重命名 parentInterfaceMethodA() 以给出一个清楚的例子来说明这通常是如何工作的(并避免负面制裁):

public interface ITreatable
{
    Treatment GetTreatment();
}

好吧,即使对象代表一种可治疗的疾病,找到治疗方法可能并不那么容易。下面是一些示例:

public class TheFlu : ITreatable
{
    public Treatment GetTreatment(int year)
    {
        // return some object, Treatment, based on the flu season.
    }
}

public class Hangover : ITreatable
{
    public Treatment GetTreatment()
    {
        return Treatment.Empty; // no parameters necessary.
    }
}

public class Insomnia : ITreatable
{
    public Treatment GetTreatment(FamilyHistory occurances, LabResult lab)
    {
        // return Some Treatment object that can be different based on the
        // calculated risk from the arguments.
    }
}

我们真正缺少的东西

我不懂生物学,但概念还是一样的。您有一组 ITreatable 疾病对象,需要有一个 GetTreatment() 方法;但是,他们使用不同的标准进行计算。我们需要症状

public class Symptoms
{
    public FamilyHistory History;
    public DateTime Time;
    public LabResult Lab;
    public BloodTest BloodTest;
    public TimeSpan SymptomTime;
    public IsCritical IsCritical;
}

现在,对象可以在自己的方法中解析症状,我们的界面将如下所示:

public interface ITreatable
{
    Treatment GetTreatment(Symptoms symptoms);
}

关于c# - 在 C# 中定义具有不同参数的接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31781696/

相关文章:

java - 如何声明包含实现接口(interface)的类的子类的变量?

c# - 如何检查我的 .NET Core 控制台应用程序是否作为独立应用程序运行(通过运行 myapp.exe)或者是否使用 dotnet myapp.dll 运行?

c# - 无法在列表 C# 中保存通用接口(interface)实现

c# - 用户控件之间的WPF MVVM切换

C# 将源文件编译为插件

javascript - AngularJS $资源参数名称

java - 将接口(interface)传递给实现该接口(interface)的类

c# - 测试 Web.Api ActionFilter 时模拟 HttpActionContext.ActionArguments

reactjs - React 和 Typescript 接口(interface) "OR"运算符

c# - 覆盖嵌套内部类中的运算符