实体类别:
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; }
}
接口:
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”的调用方法。如何编写课程?如果我将所有方法都设置为静态,问题将得到解决,但是我认为这不是一个好的解决方案。
非常感谢你!
最佳答案
通常,我建议减少类之间的耦合。每个类都应该做一件事(客户和发票),然后创建一个同时使用两者的类。例如,您可以创建一个名为“ CustomerInvoicer”的类,该类在其构造函数中使用两个接口,并将方法“ GetInvoiceCustomer”移至该新类。以我的经验,从长远来看,这将使它更具可维护性,因为每个类都有一个责任,并且最终用户只需使用一个主类(可能具有更高级的逻辑)。
public class CustomerInvoicer {
private readonly ICustomerService _customerService;
private readonly IInvoiceService _invoiceService;
public CustomerInvoicer(ICustomerService cust, IInvoiceService inv) {
_invoiceService = inv;
_customerService = cust;
}
public Customer GetInvoiceCustomer(int invoiceId) {
Invoice invoice = _invoiceService.GetInvoiceById(invoiceId);
return _customerService.GetCustomerById(invoice.CustomerId);
}
}
另外,我建议通过这种方法使用依赖注入库。
关于c# - C#中的类设计结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21200014/