开发者

Question about syntax where in the define of a class

I started to implement a repository pattern following this tutorial. Now In the definition of the class which implements the interface of Repository. The defines of the classes are made like this.

public class Repository<E,C> : IRepository<E,C>, IDisposable 
    where E : EntityObject
    where C : ObjectContext
{
}

Can someone explain me if I defined a class with generics why do i need to type where to explain which are the objects that are expected??. I'm really confused with th开发者_C百科is topic


Constraining the types with where is a deliberate choice, which has two consequences:

  1. The compiler will not allow you to write code that instantiates the generic if the type parameters do not satisfy these constraints, and in return
  2. It will allow you to use objects of class E and C as EntityObject and ObjectContext within the definition of Repository<,>; otherwise, it would not let you access members (methods, properties, etc) of those classes because it wouldn't be able to guarantee that those members exist on the types used to specify the generic.


The where specifies what can be used - in your example, E must be an EntityObject (or something that derives from EntityObject) and C must be an ObjectContext (or something that derives from ObjectContext). This is a set of constraints, that's all. Typically this is done because the class (in this case Repository) has some expectations that need to be met, at least that is how I've personally used it.


What is going on is that the generics are constrained to be that type or any type derived from that type. This is done so that certain methods, properties, events, fields, etc. become available to the generics and prevents types that don't match these constraints form being used.

You can find more information on MSDN about Generic Constraints.


why do i need to type where to explain which are the objects that are expected?

You're not saying what objects are expected. You're constraining the types to be some type that derives from that object type. However, it can be a specific subclass of that object.


You're defining a generic type constraint there - not which types are expected.

In this same way, you can require a specific type, an interface that must be implemented by your expected type, a base class, an abstract class or you can constrain the type parameter(s) as a reference type too (where T : class).

This link may be of use: Constraints on type parameters

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜