问题
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