VS2019 Roslyn Compiler Generic Constraint Method Resolution

谁说胖子不能爱 提交于 2019-12-10 22:43:16

问题


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

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 generates a compilation error stating that the int[] is not convertible to ISet.

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?


回答1:


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:

Improved overload candidates

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. When a method group contains some generic methods whose type arguments do not satisfy their constraints, these members are removed from the candidate set.
  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:

  • Expected implementation complexity
  • Expected implementation performance
  • Expected usefulness - anticipation that the previous behavior would be fine or even preferable to the current behavior, without realizing where it would be annoying in reality


来源:https://stackoverflow.com/questions/56192446/vs2019-roslyn-compiler-generic-constraint-method-resolution

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!