假设我已经建立了这样的类:返回对通用列表的引用?
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>
似乎是返回列表作为值,这就是为什么我做的任何新增内容都没有反映在主列表结构中...
那么如何返回列表作为参考,以便我可以使用该参考来做通过其他功能添加列表?
'GetLists()'没有按值返回列表。发生了什么是'aliases.Cast()。ToList();'创建一个全新的列表。 –
JLRishe
2013-02-10 16:18:23
所有的类和接口都是引用类型。 – antonijn 2013-02-10 16:18:30
@JLRishe,我看到问题..任何解决方案,不涉及代码冗余? – Ahmad 2013-02-10 16:25:29