C# Generic Method Without Specifying Type

后端 未结 3 1836
無奈伤痛
無奈伤痛 2020-12-11 15:20

Ok so I\'m a Java guy starting to use C# and I was coding and started making a generic method and what I wrote runs and compiles but it goes against everything I know about

相关标签:
3条回答
  • 2020-12-11 15:33

    C# has a great many more compile-time and runtime type inference features than Java. If this subject interests you, see my articles on the subject:

    http://blogs.msdn.com/b/ericlippert/archive/tags/type+inference/

    If you are in particular interested in generic method type inference and you have half an hour to spare, here's me explaining how we changed the type inference algorithm in C# 3:

    http://blogs.msdn.com/b/ericlippert/archive/2006/11/17/a-face-made-for-email-part-three.aspx

    0 讨论(0)
  • 2020-12-11 15:35

    The C# compiler can often infer the generic type at compile time. When it can do this, you do not need to specify the type for a generic method.

    This is a major part of what makes LINQ "usable". Without compile time type inference, queries would look like:

    IEnumerable<int> myIds = myCollection
                                 .Where<MyType>(i => i.Name == "Foo")
                                 .Select<MyType, int>(i => i.Id);
    

    Instead of being able to write:

    var myIds = myCollection.Where(i => i.Name == "Foo").Select(i => i.Id);
    
    0 讨论(0)
  • 2020-12-11 15:46

    No, it is inferred at compile time - the generic type parameter in the IEnumerable<T> you supply is used, which is known at compile time. Generally put, everything concerning generics and type parameters is specified at compile time. If there is mismatch of any kind, the compiler will complain and your code won't compile.

    There are edge cases where you have to specify the types explicitly, these only occurs in rare circumstances with overloaded methods, sometimes with multiple combinations of type parameters.

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