2015-02-05 94 views
0

我对.NET相对较新,而且我偶然发现了这个特定问题:在遵循关于存储库模式的教程时,类的定义如下所示:C#实现接口“where TEntity:class”

public class GenericRepository<TEntity> where TEntity : class { ... 

这就是说,这个类应该实现一个接口。由于我已经使用了:运营商,我该怎么做?

我试着去public class GenericRepository<TEntity> : IGenericRepository where TEntity : class {public class GenericRepository<TEntity> where TEntity : class : IGenericRepository {但它不工作

+1

你是说泛型参数应该实现一个接口还是类型本身? – 2015-02-05 21:57:25

+0

@ Selman22我认为后者(“这个类应该实现一个接口”),但目前尚不清楚。 – 2015-02-05 22:05:22

回答

2

因为我已经习惯了:运营商,我该怎么办呢?

:不是运算符 - 您只是在泛型约束中使用它。您仍然可以指定要实现的接口。

这应该是罚款:

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

或者,如果IGenericRepository是一个通用的接口,你可能想:

public class GenericRepository<TEntity> : IGenericRepository<TEntity> 
    where TEntity : class 
+0

接受这个答案,因为接口也是一个通用的,它也混淆了如何声明:'...:IGenericRepository 其中...' – 2015-02-05 22:24:36

0

使用逗号来添加多个泛型约束:

public class GenericRepository<TEntity> where TEntity : class, IGenericRepository {} 
0

你会说 public class GenericRepository<TEntity> : BaseClass1, IInterface1, IInterface2, ... where TEntity : class { ...

您使用的:指泛型类型参数需要为class(而不是struct),因此您可以添加其他“:”。

0
public class GenericRepository<TEntity> : **IGenericRepository**<TEntity> where TEntity : class 

在我的情况下,所有类都从IdentityBaseClass继承这样我的签名看起来像:

public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : IdentityBase 

这样说是什么意思是我的课,谁想用GenericRepository,必须从IdentityBase类继承。

我的IdentityBase类有两个属性。

public class IdentityBase 
    { 
     /// <summary> 
     /// Gets or sets ID. 
     /// </summary> 
     [NonNegative] 
     [DataMember(IsRequired = true)] 
     public int ID 
     { 
      get; 
      set; 
     } 

     /// <summary> 
     /// Gets or sets the unique identifier of a row; this is to do with replication in SQL. 
     /// </summary> 

     public Guid UniqueIdentifier 
     { 
      get; 
      set; 
     }