What are implied generic type parameters

前端 未结 3 717
面向向阳花
面向向阳花 2020-12-15 09:37

So, I ran across an answer by Servy ( https://stackoverflow.com/a/15098242/496680 ) and some of his code does this:

public static int BinarySearch

        
3条回答
  •  失恋的感觉
    2020-12-15 10:20

    Well, you left out the most important part that makes it all work. The type parameters can be inferred by the actual object parameters passed in.

    For instance:

    static class Extensions {
      internal static IEnumerable Test(
                                       this IEnumerable items,
                                       Func converter) {
        foreach (T item in items) {
          yield return converter(item);
        }
      }
    }
    

    This extension method works on any IEnumerable class and will convert each item in the enumeration to another type based on the converter you provided. This is standard generics.

    Now, there are many ways to call this method:

    IEnumerable values = Enumerable.Range(1, 10);
    Func converter = i => i.ToString("0.00");
    
    // Variation 1, explicit calling
    IEnumerable results1 = Extensions.Test(values, converter);
    
    // Variation 2, explicit calling with type inference
    IEnumerable results2 = Extensions.Test(values, converter);
    
    // Variation 3, extension method calling, still providing explicit types
    IEnumerable results3 = values.Test(converter);
    
    // Variation 4, extension method with type inference
    IEnumerable results4 = values.Test(converter);
    

    All four variations call the same method and return the same result. Type inference works by looking at the parameters passed and automatically inferring their types based on what's being provided. In our examples above, it's able to determine that type T is of type int because we passed in an IEnumerable into the parameter for IEnumerable. It is also able to infer that type U is of type string because we passed in a Func matching the initial type of T with int and returning a string. So the Func is filled in with our converter function of Func.

    From the inference above, it's a standard generic method at that point. Type inference and extension methods are nothing more than convenience/syntactic sugar. In fact, if you decompile the output you can see that extension methods are replaced with static calls and are usually defined with the type parameters explicitly filled out. (This varies based on your decompiler and the set options).

提交回复
热议问题