Generic constraints to a specific class, why? [duplicate]

我的梦境 提交于 2021-02-08 05:18:19

问题


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

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.

What am I missing ?


Update:

My question has been marked as duplicate for : Why use generic constraints in C#

I don't think it's the case.

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 ?


回答1:


Perhaps this simple example might help.

If I have these classes:

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());

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.



来源:https://stackoverflow.com/questions/38249592/generic-constraints-to-a-specific-class-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!