VS2019 Roslyn 编译器通用约束方法解析 [英] VS2019 Roslyn Compiler Generic Constraint Method Resolution

查看:52
本文介绍了VS2019 Roslyn 编译器通用约束方法解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们最近在我们的代码库中发现了一个问题,VS2019 编译的代码很好,但 VS 2017 失败了.

We recently found an issue in our code base, where VS2019 Compiled code fine but VS 2017 Failed.

我为 Union 创建了一个扩展方法,它有一个通用的 ISet 作为通用约束

I've created an extension method for Union which has a generic ISet as a Generic Constraint

using System;
using System.Collections.Generic;
using System.Linq;
public static class Extensions
{
    public static S Union<S, T>(this S self, IEnumerable<T> other) where S : ISet<T>, new()
    {
        //For simplicity issues since this is a compilation based question
        return default(S);
    }

    public static void Test()
    {
        var values = new[] { 1, 2, 3 };
        var values1 = new[] { 1, 2, 3, 4 };

        values.Union(values1);
    }
}

Union 生成编译错误,指出 int[] 不可转换为 ISet.

Union generates a compilation error stating that the int[] is not convertible to ISet.

我的理解是方法解析最初忽略了通用约束.不过貌似这段代码是2019年编译的.

It was my understanding that method resolution originally ignored Generic constraints. But it seems that this code Compiles in 2019.

我在发行说明中没有看到任何地方说明他们已经解决了这个错误或添加了一个新功能来改进通用方法的方法解析.

I haven't seen anywhere in the release notes which states that they've resolved this bug or added a new feature to improve method resolution for generic methods.

我正在寻找有关此事的更多信息,这是微软修复的错误还是预期的功能?

I'm looking for more information about this matter, Was this a bug fix by microsoft or an intended feature?

推荐答案

它是 C# 7.3 的一部分(因此,如果您指定版本 7.3,也可以在 VS 2017 中使用它).它记录在 C# 7.3 发行说明:

It's part of C# 7.3 (so you can use it in VS 2017 as well if you specify version 7.3). It's documented in the C# 7.3 release notes:

改进的过载候选

在每个版本中,重载解析规则都会得到更新,以解决不明确的方法调用具有明显"错误的情况.选择.此版本添加了三个新规则以帮助编译器做出显而易见的选择:

In every release, the overload resolution rules get updated to address situations where ambiguous method invocations have an "obvious" choice. This release adds three new rules to help the compiler pick the obvious choice:

  1. ...
  2. 当方法组包含一些类型参数不满足其约束的泛型方法时,这些成员将从候选集中删除.
  3. ...

这之前不是错误 - 它遵守语言规范;我不知道为什么规范最初是这样写的.可能的原因包括:

This wasn't a bug before - it was obeying the language specification; I don't know why the specification was originally written the way it was here. Possible reasons include:

  • 预期的实现复杂性
  • 预期的实施效果
  • 预期有用性 - 预期先前的行为会比当前的行为更好,甚至更可取,而没有意识到它在现实中会令人讨厌的地方

这篇关于VS2019 Roslyn 编译器通用约束方法解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆