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

前端 未结 2 1462
刺人心
刺人心 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 where T : IFirst
    {
    }
    
    // Or this one?
    public class My where T : ISecond
    {
    }
    
    public class Foo : IFirst, ISecond
    {
        public void Bar()
        {
            My myFoo = new My();
        }
    
        public void F() { }
        public void S() { }
    }
    

提交回复
热议问题