返回对通用列表的引用

本文关键字:引用 列表 返回 | 更新日期: 2023-09-27 17:58:45

假设我有这样设置的类:

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>似乎将列表作为值返回,这就是为什么我所做的任何添加都不会反映在主列表结构中。。。

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

返回对通用列表的引用

通过拥有所有的typeof()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);
    }
}

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

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);
}