gpt4 book ai didi

c# - 使用继承接口(interface)的不同对象

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

我一直在努力学习如何在 C# 中正确使用接口(interface),我想我基本上了解应该如何使用它们,但仍然对某些事情感到困惑。

我想创建一个程序,用于从销售订单或发票创建 CSV。由于它们都非常相似,我想我可以创建一个 IDocument 接口(interface),该接口(interface)可用于制作 CSV 文档。

class Invoice : IDocument
{
public Address billingAddress { get; set; }
public Address shippingAddress { get; set; }
public Customer customer { get; set; }
public List<DocumentLine> lines { get; set; }
// other class specific info for invoice goes here
}

我可以创建一个方法 CreateCSV(IDocument) 但我将如何处理与销售订单和发票不同的几个字段?这是对接口(interface)的错误使用吗?

最佳答案

您不继承接口(interface),您实现它们;在这种情况下,接口(interface)是一个抽象;它说“所有实现此接口(interface)的事物都具有以下共同特征(属性、方法等)”

在您的案例中,您发现实际上 InvoicesSales Orders 并不完全具有相同的特征。因此,从以 CSV 格式表示它们的角度来看,这不是一个很好的抽象(尽管对于其他事情,比如计算文档的值(value),它是一个很好的抽象)

虽然有很多方法可以解决这个问题,但这里有两个(很多)

将工作委托(delegate)给类(class)

您可以声明一个 ICanDoCSVToo 接口(interface),以某种表示 CSV 的结构返回文档(假设一个 CSVFormat 类包装了字段和值的集合) .然后你可以在 InvoicesSales Orders 上实现它,特别是针对那些用例,当你想将它们中的任何一个转换为 CSV 格式时,你将它们传递给ICanDoCSVToo 接口(interface)。

However I personally don't like that as you don't really want your Business Logic mixed up with your export/formatting logic - that's a violation of the SRP. Note you can achieve the same effect with abstract classes but ultimately it's the same concept - you allow someone to tell the class that knows about itself, to do the work.

通过工厂将工作委托(delegate)给专门的对象

您还可以创建一个工厂类 - 比方说一个 CSVFormatterFactory,给定一个 IDocument 对象确定要返回哪个格式化程序 - 这是一个简单的例子

public class CSVFormatterLibrary
{
public ICSVFormatter GetFormatter(IDocument document)
{
//we've added DocType to IDocument to identify the document type.
if(document.DocType==DocumentTypes.Invoice)
{
return new InvoiceCSVFormatter(document);
}
if (document.DocType==DocumentTypes.SalesOrders)
{
return new SalesOrderCSVFormatter(document);
}
//And so on
}
}

In reality, you'd might make this generic and use an IOC library to worry about which concrete implementation you would return, but it's the same concept.

然后各个格式化程序自己可以将 IDocument 转换为正确的具体类型,然后执行任何特定需要的操作来生成该专用类型的 CSV 表示。

还有其他方法可以处理此问题,但工厂选项相当简单,在您考虑其他选项时应该可以让您启动并运行。

关于c# - 使用继承接口(interface)的不同对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39858128/

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