Practical advantage of generics vs interfaces

前端 未结 8 1528
梦毁少年i
梦毁少年i 2020-11-29 02:35

What would be a practical advantage of using generics vs interfaces in this case:

void MyMethod(IFoo f) 
{
}

void MyMethod(T f) : where T : IFoo
{
         


        
8条回答
  •  长情又很酷
    2020-11-29 03:12

    Doing things like these is easier:

    void MyMethod(T f) where T : IFoo, new() {
        var t1 = new T();
        var t2 = default(T);
        // Etc...
    }
    

    Also, as you introduce more interfaces, generics may be more "gentle" to callers. For example, you can inherit a class from 2 interfaces and pass it directly, like this...

    interface IFoo {
    }
    
    interface IBar {
    }
    
    class FooBar : IFoo, IBar {
    }
    
    void MyMethod(T f) where T : IFoo, IBar {
    }
    
    void Test() {
        FooBar fb = new FooBar();
        MyMethod(fb);
    }
    

    ...while "interface-only" method would require an "intermediary" interface (IFooBar)...

    interface IFoo {
    }
    
    interface IBar {
    }
    
    interface IFooBar : IFoo, IBar {
    }
    
    class FooBar : IFooBar {
    }
    
    void MyMethod(IFooBar f) {
    }
    
    void Test() {
        FooBar fb = new FooBar();
        MyMethod(fb);
    }
    

提交回复
热议问题