Why aren't type constraints part of the method signature?

前端 未结 2 1457
刺人心
刺人心 2020-12-06 02:15

UPDATE: As of C# 7.3, this should no longer be an issue. From the release notes:

When a method group contains some generic methods w

相关标签:
2条回答
  • 2020-12-06 02:51

    If T matches multiple constraints, you create an ambiguity that cannot be automatically resolved. For example you have one generic class with the constraint

    where T : IFirst

    and another with the constraint

    where T : ISecond

    You now want T to be a class that implements both IFirst and ISecond.

    Concrete code example:

    public interface IFirst
    {
        void F();
    }
    
    public interface ISecond
    {
        void S();
    }
    
    // Should the compiler pick this "overload"?
    public class My<T> where T : IFirst
    {
    }
    
    // Or this one?
    public class My<T> where T : ISecond
    {
    }
    
    public class Foo : IFirst, ISecond
    {
        public void Bar()
        {
            My<Foo> myFoo = new My<Foo>();
        }
    
        public void F() { }
        public void S() { }
    }
    
    0 讨论(0)
  • 2020-12-06 02:55

    The C# compiler has to not consider type constraints as part as the method signature because they are not part of the method signature for the CLR. It would be disastrous if the overload resolution worked differently for different languages (mainly due to the dynamic binding that may happen at runtime and should not be different from one language to another, or else all hells would break loose).

    Why was it decided that these constraints would not be part of the method signature for the CLR is another question alltogether, and I could only make ill informed suppositions about that. I'll let the people in the know answer that.

    0 讨论(0)
提交回复
热议问题