0

假设我有这样的课程设置:

public abstract class GenericCustomerInformation
{
    //abstract methods declared here
}

public class Emails : GenericCustomerInformation
{
    //some new stuff, and also overriding methods from GenericCustomerInformation
}

public class PhoneNumber : GenericCustomerInformation
{
    //some new stuff, and also overriding methods from GenericCustomerInformation
}

//and more derivative classes for emails, addresses, etc ..

然后我有这个函数来返回一个特定的列表:

public List<GenericCustomerInformation> GetLists<T>()
{
    if (typeof(T) == typeof(Alias))
    {
        return aliases.Cast<GenericCustomerInformation>().ToList();
    }

    if (typeof(T) == typeof(PhoneNumber))
    {
        return phoneNumbers.Cast<GenericCustomerInformation>().ToList();
    }
    // .. and the same for emails, addresses, etc ..
}

现在假设我想只使用一个函数添加到这些列表中:

public void AddToList<T>(T iGenericCustomerInformation)
{
    GetLists<T>().Add((T)(object)iGenericCustomerInformation); //Doesn't work as intended. GetLists<T> seems to be returning lists as value, which is why any additions 
}

问题是AddToList<T>它不能按预期工作。GetLists<T>似乎将列表作为值返回,这就是为什么我所做的任何添加都没有反映在主列表结构中......

那么如何将列表作为参考返回,以便我可以使用该参考通过其他函数进行列表添加?

4

2 回答 2

1

typeof()通过拥有所有这些s 和if语句,您已经打败了泛型的意义。这根本不是通用的。我想说只是把if声明放在你的AddToList()方法中,然后去掉泛型。

public void AddToList(GenericCustomerInformation item)
{
    Alias aliasItem = item as Alias;
    if(aliasItem != null)
    {
        aliases.Add(aliasItem);
        return;
    }

    PhoneNumber phoneNumberItem = item as PhoneNumber;
    if(phoneNumberItem != null) 
    {
         phoneNumbers.Add(phoneNumberItem);
    }
}
于 2013-02-10T16:32:12.460 回答
0

为什么不将所有列表保存在列表字典中?

private Dictionary<Type, List<GenericCustomerInformation>> MyLists;

public List<GenericCustomerInformation> GetLists<T>()
{
    return MyLists[typeof(T)];
}

public void AddToLists<T>(GenericCustomerInformation item)
{
    GetLists<T>().Add(item);
}
于 2013-02-11T14:07:54.863 回答