开发者

C# and/or ASP.NET Class where clause?

开发者 https://www.devze.com 2023-01-20 05:31 出处:网络
I really don\'t know if this is a C# thing or an asp.net thing. I was looking at this开发者_StackOverflow中文版 article: http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-s

I really don't know if this is a C# thing or an asp.net thing. I was looking at this开发者_StackOverflow中文版 article: http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/ and ran into this line:

public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class

I'm fairly new to C#/ASP.NET so I don't fully understand this line. What does the "where TEntity : class" do? I have never created a class with a "where clause" (is that even what it's called).


It's using generics (C# thing, nothing to do with ASP.NET).

<TEntity> is a generic type parameter, meaning you must specify the type of the GenericRepository.

Like this:

var repo = new GenericRepository<Person>();

The where clause says the type you supply must be a class.

It's called a Derivation Constraint. It basically tells the compiler to enforce this constraint.

If you changed it to where TEntity : int, the above code would fail.

You would need this:

var repo = new GenericRepository<int>();

A note on <TEntity>, this is not a keyword/reserved word. You could easily change it to <FooBar> and where FooBar : class. It has the T to indicate generics, and Entity to specify the Repository works off an Entity.

Change the generic type parameter to whatever makes sense to you and your code.

By the way - that article is like my bible at the moment. :)

0

精彩评论

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