gpt4 book ai didi

c# - 泛型类型推断解释

转载 作者:行者123 更新时间:2023-11-30 12:29:13 25 4
gpt4 key购买 nike

我有以下代码:

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 年有效,以及在规范中的哪个位置对此进行了解释?

最佳答案

问题来自 VS2010 中扩展方法的类型推断。

如果你用静态方法替换扩展方法,类型推断就可以了:

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

Microsoft 在 C# 语言规范 5.0 版(请参阅第 7.5.2 节)中对此问题没有明确的回答。

有关更多信息,您可以阅读此类似问题的答案:why-doesnt-this-code-compile-in-vs2010-with-net-4-0

关于c# - 泛型类型推断解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19158132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com