类 之间的接口通信

Interface communicates between classes

接口在两个class之间通信是否正确?好像它可以将信息从 class B 发送到 class C?两个 classes 都继承相同的接口。

这个例子我看过

let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of the type "hand", named "left hand" and "right hand". Their main functions are controlled or managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface that your body uses to interact with your hands. The hand is a well-architected class. The hand is being reused to create the left hand and the right hand by slightly changing the properties of it.

这只是指定接口控制或管理class,我同意这一点,但不知何故我知道接口可以将数据从一个class传输到另一个,所以是否正确我们这样定义接口或说我们为此目的使用接口

Interface creates communication between two classes, for example Interface Iabc inherited in ClassA and ClassB then it can send information of ClassA to ClassB.

public interface  Interface1
{
    void  Method1(string msg);
     void Method2(string msg1 ,string msg2);
}
 public static class  HelperClass
 {
     public static void Method1(Interface1 obj ,string msg)
     {
         obj.Method1(msg);
     }

     public static void Method2(Interface1 obj,string msg1, string msg2)
     {
         obj.Method2(msg1,msg2);
     }
 }
  static void Main(string[] args)
    {
        var Car = new Vehcile();
        var HS = new Person();
        Car.per= "Car Clss";
        HS.per = "HS Clss";
        HelperClass.Method1(Car, Car.per);
        HelperClass.Method1(HS, HS.per);
        HelperClass.Method2(Car, Car.per, HS.per);
        HelperClass.Method2(HS, HS.per, Car.per);
        Console.ReadKey();
    }

     public class Person : Interface1
 {

    public String per;

     void Interface1.Method1(string msg)
    {
        Console.WriteLine(msg);
    }

    void Interface1.Method2(string msg1, string msg2)
    {
        Console.WriteLine("Person Class" + msg1 + " " + msg2);
    }
}

 class Vehcile : Interface1
{
    public String per;

     void Interface1.Method1(string msg)
    {
        Console.WriteLine(msg);
    }

    void Interface1.Method2(string msg1, string msg2)
    {
        Console.WriteLine("Vehcile Class" + msg1 + " " + msg2);
    }
}

Is it right to say that interface communicates between two classes?

我不会这样定义接口。我会看一个像有约束力的合同这样的界面。合同规定:"Anyone implementing this interface, must be able to do any action defined by the contract."

例如:

public interface IHand
{
    void Shake(IHand otherHand);
}

public class Hand : IHand
{
    public void Shake(IHand otherHand)
    {
        Console.WriteLine("Shook the other hand");
    }
}

IHand是一个接口,它声明了一个名为Shake的方法,该方法接收IHand的另一个对象。任何实现我们接口的 class 都必须提供一个名为 Shake 的方法,它会做一些事情。

在这个特定的例子中,我们的 Hand class 每次握手时都会写到控制台。

通过接口,我们可以创建抽象。意思是,我们可以只依赖 合约 ,而不是依赖具体的 class(例如 Hand)。这意味着,任何实现 IHand 的对象对我们来说都很好,因为它保证他会有一个我们可以调用的 Shake 方法。 Shake 方法内部发生的事情超出了我们的范围,我们通常并不关心。