Why use generic constraints in C#

前端 未结 7 1698
日久生厌
日久生厌 2020-11-29 05:48

I\'ve read an excellent article on MSDN regarding Generics in C#.

The question that popped in my head was - why should i be using generic constraints?

For ex

7条回答
  •  离开以前
    2020-11-29 06:19

    Well for a start, you can call methods defined in ISomething within the code for the generic method / methods on the generic class. If T was allowed to be any type then this would not be possible (although you could always do some runtime casting).

    So it allows you to enforce compile-time constraints on what T can be and therefore rely on these constraints when you write the code - turning runtime errors into compile time errors.

提交回复
热议问题