gpt4 book ai didi

c# - 为什么这个接口(interface)在类中是这样实现的呢?

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:23 24 4
gpt4 key购买 nike

我以前没有见过作为类成员实现的接口(interface)。有人可以解释发生了什么吗?你允许实例化一个接口(interface)吗?这些接口(interface)需要的方法的实现在哪里?

public class MyClass
{
private readonly ITest1 interface1;
private readonly ITest2 interface2;
private readonly ITest3 interface3;

public MyClass(ITest1 interface1, ITest2 interface2, ITest3 interface3)
{
this.interface1 = interface1;
this.interface2 = interface2;
this.interface3 = interface3;
}

public void TestMethod()
{
var lines = interface1.GetData();
var file = interface2.Parse(lines);
interface3.Copy(file);
}
}

与我通常使用接口(interface)的方式相比有什么区别:

public class Person : IEquatable<Dog>
{
public int Age { get; set; }

public bool Equals(Dog d)
{
if (d.Age == this.Age)
return true;
else
return false;
}
}

public class Dog
{
public int Age { get; set; }
}

最佳答案

区别在于:

您对Person 类所做的是接口(interface)实现

MyClass 没有实现任何接口(interface),但它接受接口(interface)作为构造函数参数。调用构造函数的人将提供实现接口(interface)的实例。更多内容如下。

Are you allowed to instantiate an interface?

没有。实现该接口(interface)的类将被实例化。

Where is the implementation of the methods required by these interfaces?

当此人创建您的类的实例时,他们将传递一个实现该接口(interface)的类的实例。像这样:

public interface ITest1
{
string GetData();
}
public class Test1 : ITest1
{
public string GetData()
{
return "Data";
}
}

他们会这样称呼你的类(class):

var test1 = new Test11();

// instead of nulls it will be other instances like test1
var myClass = new MyClass(test1, null, null);

I have not seen interfaces implemented as class members before. Can someone explain what's going on?

上面我已经用例子解释了这是怎么回事。

这其实是一种很常见的方式,是的还有其他方式,但这是其中一种方式。

优势

  1. 这样您的 MyClass 不知道将传递什么具体类型,但它知 Prop 体类型是什么,它都会支持接口(interface)。

  2. MyClass 中,您将只有依赖于接口(interface)的代码,因此您的类是松散耦合的。

  3. 依赖注入(inject)可用于将依赖注入(inject)到MyClass 的构造函数中。这就是所谓的构造函数注入(inject)。

What's the difference compared to the way I've normally used interfaces:

没有区别。但是您需要考虑人们将如何使用该类(class)。例如,如果您想使用 MyClass,您将按照您习惯的方式执行此操作:

public class Test1 : ITest1
{
public string GetData()
{
return "Data";
}
}

为了进一步说明,假设 MyClass 有另一个构造函数和字段,如下所示:

private readonly IEquatable<Dog> iEq;
public MyClass(IEquatable<Dog> iEq) { this.iEq = iEq; }

然后您将使用您的 Person 类的实例调用它。所以它没有任何不同。

注意:没有人会乐意被等同于狗;)

关于c# - 为什么这个接口(interface)在类中是这样实现的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42661156/

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