简体   繁体   中英

Generic type inference explanation

I have the following piece of code:

namespace ConsoleApplication1
{
    using System.Collections.Generic;
    using System.Linq;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var bar = new object();

            var result = new int[] { 1, 2, 3 }
                .Select/* <int,int> */(bar.Test<int>)
                .ToList();
        }
    }

    public static class Extensions
    {
        public static TReturnType Test<TReturnType>(this object o, int e)
        {
            return default(TReturnType);
        }
    }
}

Compiling this on a machine with only Visual Studio 2012 works like a charm. However to compile it on a machine with just 2010 it is required that you remove the comment around the <int, int> .

Can somebody elaborate on why this now works in 2012, and where in the spec this is explained?

The problem comes from type inference of an extension method in VS2010.

If you replace the extension method by a static method, type inference will be ok :

namespace ConsoleApplication1
{
    using System.Collections.Generic;
    using System.Linq;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var result = new int[] { 1, 2, 3 }
                .Select/* <int,int> */(Extensions.Test<int>)
                .ToList();
        }
    }

    public static class Extensions
    {
        public static TReturnType Test<TReturnType>(int e)
        {
            return default(TReturnType);
        }
    }
}

There is no clear answer from Microsoft about this question in C# Language Specification version 5.0 (see section 7.5.2).

For more information, you can read the answers at this similar question : why-doesnt-this-code-compile-in-vs2010-with-net-4-0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM