C# Generic Method Without Specifying Type

后端 未结 3 1838
無奈伤痛
無奈伤痛 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: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 myIds = myCollection
                                 .Where(i => i.Name == "Foo")
                                 .Select(i => i.Id);
    

    Instead of being able to write:

    var myIds = myCollection.Where(i => i.Name == "Foo").Select(i => i.Id);
    

提交回复
热议问题