特定类的通用约束,为什么? [英] Generic constraints to a specific class, why?
问题描述
我一直在阅读利用泛型约束的知识,发现泛型可以限制为 struct
, class
, new
, Class
和 Interface
.前三个背后的原因非常明显.但是我真的不明白为什么和何时约束一个班级.即
I've been reading on leveraging generic constraints, I've found that generics can be constrained to struct
, class
, new
, Class
and Interface
. The reasons behind the first three are pretty obvious. But I can't really understand why and when to constraint to a class. i.e
class Foo<T> where T : Bar
class Foo<T> where T : IBar
这使我们可以限制Bar和它的孩子,分别限制IBar和实现者.我们不能只为类或接口编程吗?因为这基本上就是多态性的用途,并且Microsoft工程师绝不会愚蠢地实现无用的功能.
This allows us to constrain to Bar and it's children, and IBar and implementers respectively. Can't we just program to the class, or the interface ? Because that's basically what polymorphism is for, and Microsoft Engineers are far from dumb to implement a useless feature.
我想念什么?
更新:
我的问题已被标记为重复:为什么在C#中使用泛型约束
My question has been marked as duplicate for : Why use generic constraints in C#
我认为并非如此.
我彻底解决了这个问题,但并没有真正找到答案:它讨论了一般约束的使用,而在这里我问的是为什么我们要约束到一个类或一个接口上,为什么不仅仅局限于此呢?直接编程吗?
I went through this question thoroughly, and didn't really find the answer: It discussed the use of generic constraints in general, while here I'm asking about why do we constrain to a class or an interface, why not just program to it directly ?
推荐答案
也许这个简单的示例可能会有所帮助.
Perhaps this simple example might help.
如果我有这些课程:
public class ListOfCars<T> : List<T> where T : Car { }
public abstract class Car { }
public class Porsche : Car { }
public class Bmw : Car { }
...然后,如果我编写这段代码:
...and then if I write this code:
var porsches = new ListOfCars<Porsche>();
// OK
porsches.Add(new Porsche());
//Error - Can't add BMW's to Porsche List
porsches.Add(new Bmw());
您会看到我无法将BMW添加到保时捷列表中,但是如果我只是在基类基础上进行编程,那将是允许的.
You can see that I can't add a BMW to a Porsche list, but if I just programmed off of the base class it would be allowed.
这篇关于特定类的通用约束,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!