gpt4 book ai didi

c# - 不使用接口(interface)掌握 API

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

我刚刚获得了一个 API,它似乎比我习惯的更上一层楼,因为一切似乎都是使用接口(interface)实现的,我正在努力理解它们。

public partial class Form1 : Form, IFoo
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Guid jobID = AddBarToFoo(fooID, barPath);
}

public Guid IFoo.AddBarToFoo(string fooID, string barPath)
{
throw new NotImplementedException();
}

这是一个基本结构。 Visual Studio 已经完整地实现了接口(interface),我可以调用 AddBarToFoo 方法。伟大的。

但是现在呢?显然该方法是一个 void,需要一些代码,但是什么代码呢?我是否应该在 API 中搜索对象以使用该方法实例化?还是我完全走错了路?

最佳答案

接口(interface)就是这样。他们只定义某人如何称呼他们。他们绝对没有说该方法应该做什么,或者应该如何做。这由实现接口(interface)的人决定。

VS 通过添加单行 throw new NotImplementedException(); 来“实现”该方法,这实际上只是为了满足编译器。

这里有两个可能的(人为的)实现,它们做完全不同的事情。两者都实现了 IFoo:

public class DbFoo:IFoo {
public Guid IFoo.AddBarToFoo(string fooID, string barPath) {
// this might add a Foo to the database and return its Guid
}
}

public class ListBasedFoo:IFoo {
public ListBasedFoo() { MyList = new List<Foo>(); }

public List<Foo> MyList { get; private set; }

public Guid IFoo.AddBarToFoo(string fooID, string barPath) {
// this could add a Foo to MyList, and return some Guid to reference it
}
}

编辑... 您会看到在抽象行为 很重要的地方经常使用接口(interface),但实现可能会有所不同。例如,持久化对象的接口(interface)。在开发过程中,您可能希望使用模拟将项目放入和获取内存中的列表。稍后您可能会使用通过 ADO .NET 或 Entity Framework 或 LINQ to SQL 直接访问数据库的接口(interface)。也许在应用程序生命周期的另一个时刻,将放弃使用 WCF Web 服务的新实现。

在我上面的示例中,要点是调用代码 不会中断。 界面很满意 - 只有行为发生了变化。

关于c# - 不使用接口(interface)掌握 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9096925/

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