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

后端 未结 7 965
被撕碎了的回忆
被撕碎了的回忆 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:05

    The generic version will require .NET 2.0.

    But seriously, while they look similar, there are fundamental differences between them. One difference is, at runtime, the JIT compiler will generate code for each value type that will be used for the generic version. The non-generic version will require the value types to be boxed in order to be passed to the function.

    The difference will also matter when dealing with delegates. The signature of MyMethod matches void MyDelegate(int x) while the non-generic version is not matched.

提交回复
热议问题