在您的公司中,假设您有以下代码:
public abstract Phone
{
public int PhoneID {get;set;}
public string PhoneNumber {get;set;}
}
public CustomerPhone : Phone
{
public int CustomerID {get;set;}
}
public AccountPhone : Phone
{
public int AccountID {get;set;}
}
这应该意味着我们有多种类型的电话,一些是客户电话,一些是帐户电话,等等......
问题是“这可能吗?如果可以,那怎么办?” 似乎最简单的方法是拥有一个可以插入类型的通用电话类,然后它会在需要时使用该类型的信息(AccountID 或 CustomerID)。我还在检查是否可以在没有 DI 的情况下执行此操作(无论是通过构造函数、方法还是属性。)
我脑子里的东西看起来像这样:
public interface IUsePhone
{
int GetOwnerID();
}
public class Phone<T> where T : IUsePhone
{
//all of Phone's properties from above.
public int GetOwnerID()
{
//return T or item or something's GetOwnerID();
}
}
public class Account : IUsePhone
{
private int _accountID;
//other Account members, including an AccountID property.
public int GetOwnerID()
{
return _accountID;
}
public Phone<Account> Phone { get; set; }
}
public class Customer : IUsePhone
{
private int _customerID;
//other Customer members, including an CustomerID property.
public int GetOwnerID()
{
return _customerID;
}
public Phone<Customer> Phone { get; set; }
}
这不会编译,因为 Phone 的 GetOwnerID() 当前没有任何方法来返回它的所有者的 GetOwnerID() 结果。我希望从客户的角度来看的最终结果可能是这样的:
Account myAccount = new Account();
myAccount.AccountID = 10;
int ownerID = myAccount.Phone.GetOwnerID(); //this would return 10.