4

我有以下代码:

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);
        }
    }
}

在只有 Visual Studio 2012 的机器上编译它就像一个魅力。但是,要在只有 2010 的机器上编译它,您需要删除<int, int>.

有人可以详细说明为什么这现在在 2012 年有效,并且在规范中对此进行了解释吗?

4

1 回答 1

2

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

于 2013-10-03T13:12:21.767 回答