我有一个Loan
班:
public class Loan
{
public int ID { get; set; }
public int ClientID { get; set; }
public string PropertyAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
//etc..
}
还有一个类Client
:
public class Client
{
public int ID { get; set; }
public string Company { get; set; }
public string FirstName { get; set; }
public string Address { get; set; }
// etc..
}
我需要一个ClientWithLoan
对象,因为C#中没有多重继承,那么正确的模式是什么?
答案 0 :(得分:4)
两个选项:
如果ClientWithLoan
与Client
是不同的类型,则可以这样操作:
class ClientWithLoan : Client
{
public Loan Loan { get; set; }
}
您可能还需要一些验证:
class ClientWithLoan : Client
{
protected Loan _loan;
public Loan Loan
{
get { return _loan; }
set
{
if (value.ClientID != this.ID) throw ArgumentException();
_loan = value;
}
}
}
只需将Loan
属性添加到您的Client类,并在该特定客户没有贷款的情况下将其保留为空。
public class Client
{
public int ID { get; set; }
public string Company { get; set; }
public string FirstName { get; set; }
public string Address { get; set; }
public Loan Loan { get; set; }
}
答案 1 :(得分:3)
当您需要一种继承单一语言的多种继承时,使用接口通常可以解决问题。
您可以通过以下方式做到这一点:
public interface ILoan
{
public int ID { get; set; }
public int ClientID { get; set; }
public string PropertyAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
//etc..
}
public interface IClient
{
public int ID { get; set; }
public string Company { get; set; }
public string FirstName { get; set; }
public string Address { get; set; }
// etc..
}
public interface IClientWithLoan: IClient, ILoan
{
}
public sealed class ClientWithLoan: IClientWithLoan
{
// here place the real implementation
}
这种方法为您提供了所需的灵活性。