2013-02-10 59 views
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>似乎是返回列表作为值,这就是为什么我做的任何新增内容都没有反映在主列表结构中...

那么如何返回列表作为参考,以便我可以使用该参考来做通过其他功能添加列表?

+2

'GetLists()'没有按值返回列表。发生了什么是'aliases.Cast ()。ToList();'创建一个全新的列表。 – JLRishe 2013-02-10 16:18:23

+0

所有的类和接口都是引用类型。 – antonijn 2013-02-10 16:18:30

+0

@JLRishe,我看到问题..任何解决方案,不涉及代码冗余? – Ahmad 2013-02-10 16:25:29

回答

1

您已经通过声明了所有那些typeof()if声明来击败泛型。这根本不是通用的。我只是说if声明在你的AddToList()方法和nix的泛型。

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