Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 继承和接口分离原则_C#_Inheritance_Solid Principles_Interface Segregation Principle - Fatal编程技术网

C# 继承和接口分离原则

C# 继承和接口分离原则,c#,inheritance,solid-principles,interface-segregation-principle,C#,Inheritance,Solid Principles,Interface Segregation Principle,从具有未使用方法的类继承是否违反了接口隔离原则 例如: abstract class Base { public void Receive(int n) { // . . . (some important work) OnMsg(n.ToString()); } protected abstract void OnMsg(string msg); } class Concrete : Base { protected

从具有未使用方法的类继承是否违反了接口隔离原则

例如:

abstract class Base
{
    public void Receive(int n)
    {
        // . . . (some important work)

        OnMsg(n.ToString());
    }

    protected abstract void OnMsg(string msg);
}

class Concrete : Base
{
    protected override void OnMsg(string msg)
    {
        Console.WriteLine("Msg: " + msg);
    }
}
Concrete
依赖于方法
Base.Receive(int n)
,但它从不使用它

UPD

我使用的定义:

ISP声明不应强迫任何客户端依赖于它 不使用

我看不出具体的“依赖”于Base.Receive()的方式与我使用该术语的方式相同。如果接收被修改,具体需要如何改变?我会争辩,一点也不会。假设我们将Receive()替换为具有不同名称或签名的方法,Concrete将不知道。具体调用Receive()吗?没有。所以我看不到对Receive()的依赖

依赖项具有签名OnMsg(),具体参与与Base的非常特殊的关系,实现OnMsg()契约


但从另一个意义上讲,混凝土在很大程度上依赖于Base.Receive(),它是混凝土与外部世界的接口——没有这种方法,任何人都无法访问混凝土的功能。从这个意义上说,具体地“使用”Base.Receive()是非常基本的

我认为您误解了接口隔离原则的含义。在您的情况下,您很好,没有“强制”任何实现。事实上你是在申请

如果你有一个假设

interface ICommunicateInt
{
  int Receive();
  void Send(int n);
}
为了实现它,您的
Base
类将被迫实现它不需要的
Send
方法。 因此,ISP建议最好有:

interface ISendInt
{
  void Send(int n);
}

interface IReceiveInt
{
  int Receive();
}
因此,您的类可以选择实现一个或两个。其他类中需要可以发送Int的类的方法也可能需要

void Test(ISendInt snd)
// void Test(ICommunicateInt snd) // Test would "force" snd to depend on 
                                  // a method that it does not use 

我不确定在这个例子中它没有使用它,如果没有使用Receive,如何调用OnMsg?在我的例子中,调用
OnMsg
的唯一方法是从
Receive
。我需要这个继承来将传入数据(
intn
)投影到
Concrete
的接口,该接口使用
string msg
。在实际示例中,有一些比
ToString()
@astef更复杂的工作:正如Paulo正确指出的,您正在使用
模板设计模式(此处:)我理解您。但答案是什么?将未知的传入数据投射到目标接口是一种不好的方式吗?不,这是一种非常重要的模式。