[英]can any one explain the hierarchy tree public interface IGenericRepository<T> where T: class?
we write the code and when we will use generic repo pattern but can anyone explain this convention please?我们编写代码以及何时使用通用 repo 模式,但是谁能解释一下这个约定? so can anyone explain this code so we can understand how this inheritance works.
所以任何人都可以解释这段代码,以便我们了解这个 inheritance 是如何工作的。
public interface IGenericRepository < T > where T: class
This is not inheritance;这不是 inheritance; it is a Type Constraint .
它是一个类型约束。
It limits your developers to not use classes in your Generic Repository that are not an actual representation of a DB object.它限制您的开发人员在您的通用存储库中不使用不是 DB object 的实际表示的类。
Imagine, that all your mapped entities implement an Id
field of type Guid
.想象一下,您的所有映射实体都实现了一个类型为
Guid
的Id
字段。 You can constraint your repositories to only be usable with objects that have that Id:您可以将存储库限制为仅可用于具有该 ID 的对象:
public interface IEntity
{
public Guid Id
}
public interface IGenericRepository < T > where T: IEntity
Your Generic Repo will be limited to types which implement that specific interface, and you would be sure that all concrete implementations have Guid Id
property.您的 Generic Repo 将仅限于实现该特定接口的类型,并且您将确保所有具体实现都具有
Guid Id
属性。
There is no inheritance happening in public interface IGenericRepository<T> where T: class
.在
public interface IGenericRepository<T> where T: class
。
where T: class
is a generic constraint requiring T
to be a reference type (non-nullable reference type since C#8 within nullable context ): where T: class
是一个通用约束,要求T
是一个引用类型(自C#8 以来的可空上下文中的非可空引用类型):
where T: class
- The type argument must be a reference type.where T: class
- 类型参数必须是引用类型。 This constraint applies also to any class, interface, delegate, or array type.此约束也适用于任何 class、接口、委托或数组类型。 In a nullable context in C# 8.0 or later,
T
must be a non-nullable reference type.在 C# 8.0 或更高版本中的可为空上下文中,
T
必须是不可为空的引用类型。
ie you can't create for example a IGenericRepository
of int
( IGenericRepository<int>
) cause it will not compile, but you can create repository for example of some custom class - IGenericRepository<MyClass>
.即,您不能创建例如
int
( IGenericRepository<int>
) 的IGenericRepository
,因为它不会编译,但您可以创建例如一些自定义 class - IGenericRepository<MyClass>
的存储库。 Quite often such restriction comes from repos build on top of EF Core (though some would argue that using generic repository pattern with EF is actually antipattern), cause it requires entity types to be constrained to class
.这种限制通常来自构建在 EF Core 之上的 repos(尽管有些人会争辩说,将通用存储库模式与 EF 一起使用实际上是反模式),因为它需要将实体类型限制为
class
。
Related:有关的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.