interface as argument or generic method with where - what is the difference?

前端 未结 4 1549
灰色年华
灰色年华 2021-01-17 11:46

Is any difference between :

public void Method1(class1 c, T obj) where T:Imyinterface

And

public void Method2(clas         


        
4条回答
  •  我在风中等你
    2021-01-17 12:32

    While in your scenario it's practically the same (except for the fact that with method accepting interface parameter it will upcast concrete object to interface type) consider slightly different scenario. Let's say we want our method to accept only class that implements two interfaces IMyInterface1 and IMyInterface2 and that otherwise code should not compile :

    interface IMyInterface1 { }    
    
    interface IMyInterface2 { }
    
    class MyClass : IMyInterface1 { }
    
    public void Method1(Class1 c, T obj) where T : IMyInterface1, IMyInterface2
    {
    
    }
    

    If we create method that accepts interface as it's second parameter it will not satisfy the condition because it doesn't restrict user from sending class instance that implements only one interface but doesn't implements the second interface like it is for MyClass and IMyInterface2 in this example.

    And what interface should user send ? He don't really know the type that needs to send on compile-time.

    This is a good spot to use generic and generic constrains and on the other hand we cannot use single interface parameter.

提交回复
热议问题