Generics: Why can't the compiler infer the type arguments in this case?

前端 未结 3 2061
忘掉有多难
忘掉有多难 2020-11-30 13:54

I wanted to write an extension-method that would work on dictionaries whose values were some sort of sequence. Unfortunately, the compiler can\'t seem to infer the generic a

3条回答
  •  余生分开走
    2020-11-30 14:42

    C# type inference doesn't work off of constraints or return values. So you'll have slightly better luck with

    public static void SomeMethod
        (this IDictionary> dict)
      { }
    

    This will work if you declare the param as new Dictionary< string, IEnumerable>(), but not if you declare it new Dictionary>().

    I do have to say, that the way I read section 7.5.2 of the c# spec, it seems that since List implements IEnumerable, the type inference of TUnderlyingValue should work. However, that section isn't exactly straightforward to understand. I assume it does not work through the multiple "layers", since SomeMethod(IEnumberable val){} would work just fine calling it with SomeMethod(new List()). I don't specifically see anything in the spec that deals with resolving a type where U = Ca>, so perhaps inference at that level is not defined.

提交回复
热议问题