Difference between generic argument constrained to an interface and just using the interface

后端 未结 7 964
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 17:40

What is the difference between this:

void MyMethod(IMyInterface value)
{
    //...
}

and this:

void MyMethod(T val         


        
7条回答
  •  情深已故
    2020-12-17 18:06

    Another subtle difference is that you can't overload a method only on constraints (constraints aren't part of the signature of the method):

    This is illegal:

    void MyMethod(T value) where T : IMyInterface
    {
        //...
    }
    
    void MyMethod(T value) where T : IMyInterface2
    {
        //...
    }
    

    while this is legal:

    void MyMethod(IMyInterface value)
    {
        //...
    }
    
    void MyMethod(IMyInterface2 value)
    {
        //...
    }
    

提交回复
热议问题