gpt4 book ai didi

c# - C#中的类设计结构

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

实体类:

public class Customer {
public int CustomerId { get; set; }
public string Name { get; set; }
}

public class Invoice {
public int InvoiceId { get; set; }
public int CustomerId { get; set; }
public string InvoiceNo { get; set; }
}

接口(interface):

public interface ICustomerService {
Customer GetCustomerById(int customerId);
void DeleteCustomer(int customerId);
}

public interface IInvoiceService {
Invoice GetInvoiceById(int invoiceId);
void DeleteInvoice(int invoiceId);
List<Invoice> GetAllInvoiceByCustomer(int customerId);
Customer GetInvoiceCustomer(int invoiceId);
}

类:

public class CustomerService : ICustomerService {

private readonly IInvoiceService _invoiceService = new InvoiceService();

public Customer GetCustomerById(int customerId) {
//return customer from db
return new Customer();
}

public void DeleteCustomer(int customerId) {
var invoiceList = _invoiceService.GetAllInvoiceByCustomer(customerId);
foreach (var invoice in invoiceList) {
_invoiceService.DeleteInvoice(invoice.InvoiceId);
}

//delete customer from db

}
}

public class InvoiceService : IInvoiceService {

private readonly ICustomerService _customerService = new CustomerService();

public Invoice GetInvoiceById(int invoiceId) {
//return invoice from db
return new Invoice();
}

public void DeleteInvoice(int invoiceId) {
//delete invoice from db
}

public List<Invoice> GetAllInvoiceByCustomer(int customerId) {
//get all invoice by customer id
return new List<Invoice>();
}

public Customer GetInvoiceCustomer(int invoiceId) {
Invoice invoice = GetInvoiceById(invoiceId);
return _customerService.GetCustomerById(invoice.CustomerId);
}

}

当我为“CustomerService”创建一个新实例时。它将返回一个错误:

An unhandled exception of type 'System.StackOverflowException' occurred

因为当我为“CustomerService”创建新实例时,“CustomerService”会为“InvoiceService”创建一个新实例,“InvoiceServer”也会创建一个“CustomerServer”的新实例。

1) 我应该将所有方法都设置为静态吗?

2) “InvoiceService”将调用“CustomerService”的方法,“CustomerService”也会调用“InvoiceSercie”的方法。我该如何编写类(class)?如果我将所有方法设置为静态,问题将得到解决,但我想这不是一个好的解决方案。

非常感谢!

最佳答案

您必须选择其中一个类将其自身作为对另一个类的引用。假设它是客户服务:

public class CustomerService : ICustomerService {

private readonly IInvoiceService _invoiceService = new InvoiceService(this);

...
}

public class InvoiceService : IInvoiceService {

private readonly ICustomerService _customerService;

public class InvoiceService(ICustomerService customerService) {
_customerService = customerService;
}

}

现在这个循环被打破了...

另一种选择是使用依赖注入(inject)框架,如 StructureMap 或 Ninject。

关于c# - C#中的类设计结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21200014/

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