【问题标题】:Return reference to a generic list?返回对通用列表的引用?
【发布时间】: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&lt;T&gt; 没有按预期工作。 GetLists&lt;T&gt; 似乎将列表作为值返回,这就是为什么我所做的任何添加都没有反映在主列表结构中...

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

【问题讨论】:

  • GetLists() 没有按值返回列表。正在发生的事情是 aliases.Cast&lt;GenericCustomerInformation&gt;().ToList(); 正在创建一个全新的列表。
  • 所有的类和接口都是引用类型。
  • @JLRishe,我看到了问题.. 任何不涉及代码冗余的解决方案?

标签: c# list pass-by-reference


【解决方案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);
    }
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 2017-02-10
      • 2020-12-01
      相关资源
      最近更新 更多