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

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

What is the difference between this:

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

and this:

void MyMethod(T val         


        
7条回答
  •  萌比男神i
    2020-12-17 17:59

    Jared has mentioned some of the points; another interesting one: with generics, you can avoid boxing of value-types as long as you basically don't touch it... so I could have a struct Foo : IMyInterface and pass it in, and it won't get boxed.

    The difference gets more noticeable with things like collections:

    static void Foo(IEnumerable data) {}
    

    vs

    static void Foo(IEnumerable data) 
        where T : IMyInterface {}
    

    Now, since C# 3.0 doesn't have covariance (except for arrays), I can't pass a List to the top one, even if Bar : IMyInterface - but I can with the second (implicit T = Bar).

提交回复
热议问题