1

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

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.
4

2 回答 2

4

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

如果您真的想要一堆不同的类型,所有这些类型都已Phone履行合同,那么您最好使用一个接口,再加上一个抽象的基础实现:

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;}
}
于 2012-11-28T21:19:45.943 回答
0

我认为您的示例很好 - 只是缺少接受实现 IUsePhone 的所有者实例(帐户、客户等)的构造函数。

尝试将此添加到您的Phone<T>课程中。

    public IUsePhone Owner { get; private set; }

    public Phone(T owner)
    {
        this.Owner = owner;
    }

    public int GetOwnerID()
    {
        return this.Owner.GetOwnerID();
    }

注意:在您的示例中,不要忘记您必须先设置 Phone 属性才能myAccount.Phone.GetOwnerID();调用。

如果你这样做,我会沿着已经建议的抽象基类路线走下去,并将电话设置在一个基本方法中,如下所示:

public virtual void SetPhoneNumber<T>(string number)
    {
        this.Phone = new Phone<T>(this);
        this.Phone.Number = number;
    }

所以你的使用最终会是这样的:

    Account myAccount = new Account();
    myAccount.AccountID = 10;

    myAccount.SetPhoneNumber("123456");

    int ownerID = myAccount.Phone.GetOwnerID(); // this would return 10.
于 2012-11-28T21:38:04.513 回答