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

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

    Another caveat to consider with this scenario is the fact that using "where T : <%your base interface or abstraction%>" can be overused in generics rendering your generic type non-generic in nature.

    IE: Remember that by isolating your generic method to IMyInterface, you're isolating that method to only those types implementing IMyInterface. So if you've merely chosen to use IMyInterface based on good OOP principles, but you have only one (or in some cases a very small number of) potential type anywhere that'll be implementing that interface, then you've defeated the purpose of using generics. Under that circumstance, the first option would be better.

    Only use "where" on your generic type when you're going to have a broader range of types that actually implement IMyInterface.

提交回复
热议问题