首页 > 解决方案 > C#, overload for single T and for IEnumerable

问题描述

public static void AddOrUpdate<T>(T entry) where T : class
{
        //stuff
}

public static void AddOrUpdate<T>(IEnumerable<T> entries) where T : class
{
    foreach (var entry in entries)
    {
        //stuff
    }

No matter what I send into this method, the first one is always chosen. How do I separate IEnmuerables and single objects?

AddOrUpdate(entry); //goes into first one
AddOrUpdate(new Analog[] { entry}); //still goes into first one

标签: c#objectmethodsoverloadingienumerable

解决方案


Given that you don't want to change the method declarations at all, there are two ways I can think of to make the compiler prefer the second one when you call the method.

  • specify the generic parameter:

    AddOrUpdate<Analog>(new Analog[] { entry });
    
  • make the argument of the compile time type IEnumerable<Analog>:

    IEnumerable<Analog> x = new Analog[] { entry };
    AddOrUpdate(x);
    // or
    AddOrUpdate(new string[] {""}.AsEnumerable());
    

推荐阅读