Implicit conversion fails when changing struct to sealed class

前端 未结 2 1064
半阙折子戏
半阙折子戏 2021-02-05 16:41

Struct/class in question:

public struct HttpMethod
{
    public static readonly HttpMethod Get = new HttpMethod(\"GET\");
    public static readonly HttpMethod P         


        
2条回答
  •  轮回少年
    2021-02-05 17:15

    Things I know:

    • Plainly the problem is in type inference.
    • In the first case, T is deduced to be HttpMethod1.
    • In the struct case, there is no conversion from HttpMethod1[] to IEnumerable because covariance only works on reference types.
    • In the class case, there is no conversion from HttpMethod2[] to IEnumerable because covariance only works on reference conversions, and this is a user-defined conversion.

    Things I suspect but need to confirm:

    • Something about the slight difference between my last two points is confusing the type inference algorithm.

    UPDATE:

    • It has nothing to do with covariant array conversions. The problem repros even without array conversions.
    • It does however have to do with covariant interface conversions.
    • It has nothing to do with strings. (Strings are often a bit weird because they have a hard-to-remember conversion to IEnumerable that occasionally messes up type inference.)

    Here's a program fragment that displays the problem; update your conversions to convert to C instead of string:

    public interface IFoo {}
    public class C {}
    public class Program
    {
        public static bool Contains(IFoo items, T item) 
        {
            System.Console.WriteLine(typeof(T));
            return true; 
        }
        public static void Main()
        {
            IFoo m1 = null;
            IFoo m2 = null;
            var res1 = Contains(m1, new C()); //works
            var res2 = Contains(m2, new C()); //doesn't work
        }
        }
    

    This looks like a possible bug in type inference, and if it is, it is my fault; many apologies if that is the case. Sadly I do not have time to look into it further today. You might want to open an issue on github and have someone who still does this for a living look into it. I would be fascinated to learn what the result was, and if it turns out to be a bug in either the design or the implementation of the inference algorithm.

提交回复
热议问题