【发布时间】:2013-01-25 19:43:00
【问题描述】:
假设我有这样的课程设置:
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<GenericCustomerInformation>().ToList();正在创建一个全新的列表。 -
所有的类和接口都是引用类型。
-
@JLRishe,我看到了问题.. 任何不涉及代码冗余的解决方案?
标签: c# list pass-by-reference