gpt4 book ai didi

c# - 接口(interface)在类之间通信

转载 作者:行者123 更新时间:2023-11-30 14:53:14 25 4
gpt4 key购买 nike

接口(interface)是两个类之间通信的说法对吗?就像它可以将信息从 B 类发送到 C 类?这两个类都继承了相同的接口(interface)。

我看过的这个例子

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.

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

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?

我不会这样定义接口(interface)。我会看一个像有约束力的契约(Contract)这样的界面。契约(Contract)规定:“任何实现此接口(interface)的人都必须能够执行契约(Contract)定义的任何操作。”

例如:

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

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

IHand 是一个接口(interface),它声明了一个名为Shake 的方法,该方法接收另一个IHand 对象。任何实现我们接口(interface)的类都必须提供一个名为 Shake 的方法,该方法可以执行某些操作。

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

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

关于c# - 接口(interface)在类之间通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com