2015-02-05 290 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; 
     }