Practical advantage of generics vs interfaces

前端 未结 8 1520
梦毁少年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:22

    • Calling a method through an interface is slower than calling it directly on the concrete type
    • If the type implementing IFoo is a value type, the non-generic version will box the value of the parameter, and boxing can negatively affect performance (especially if you call this method very often)
    • If your method returns a value, the generic version can return a T rather than a IFoo, which is convenient if you need to call a method of T on the result

提交回复
热议问题