Skip to main content
 首页 » 编程设计

c#之如何使用泛型而不是继承来拥有多个版本的东西

2024年02月20日11me-sa

在你的公司,假设你有以下代码:

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. 

请您参考如下方法:

我认为您需要问问自己为什么要这样做。

如果你真的想要一堆不同的类型,所有这些类型都满足了 Phone 契约,你最好使用一个接口(interface),再加上一个抽象的基础实现:

public interface IPhone 
{ 
    int PhoneID {get;set;} 
    string PhoneNumber {get;set;} 
} 
 
public abstract AbstractPhoneBase : IPhone 
{ 
    public int PhoneID {get;set;} 
    public string PhoneNumber {get;set;} 
} 
 
public CustomerPhone : AbstractPhoneBase 
{ 
    public int CustomerID {get;set;} 
}