Method overloads which differ only by generic constraint

前端 未结 2 1675
生来不讨喜
生来不讨喜 2020-12-17 08:43

I\'ve run into a bit of a problem, which I simply cannot find a good work-around to.

I want to have these 3 overloads:

public IList GetList&         


        
相关标签:
2条回答
  • 2020-12-17 09:30

    what about this?

    public IList<T> GetList<T>(string query) where T : new()
    {
      // whatever you need to distinguish, this is a guess:
      if (typeof(T).IsPrimitiveValue)
      {
        GetPrimitiveList<T>(query);
      }
      else if (typeof(T) == typeof(string))
      {
        GetStringList<T>(query);
      }
      else
      {
        GetEntityList<T>(query);
      }
    
    }
    
    private IList<T> GetStringList<T>(string query)
    
    private IList<T> GetPrimitiveList<T>(string query)
    
    private IList<T> GetEntityList<T>(string query)
    
    0 讨论(0)
  • 2020-12-17 09:42

    As you note; there aren't any good options for this. You might consider different names (rather than overloads) - GetStringList etc.

    However, I wonder whether it would be simpler to drop the constraint. A single type-check with "as" isn't exactly "heavy" type-casting, and it might save a lot of pain.

    0 讨论(0)
提交回复
热议问题