C#实现接口"其中TEntity:class"

时间:2015-02-05 21:52:44

标签: c# generics interface generic-constraints

我对 .NET 相对较新,我偶然发现了这个特定问题:在关注存储库模式的教程时,类的定义如下:< / p>

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

话虽这么说,这个类应该实现一个接口。由于我已经使用了:运算符,我该怎么做?

我尝试了public class GenericRepository<TEntity> : IGenericRepository where TEntity : class {public class GenericRepository<TEntity> where TEntity : class : IGenericRepository {,但它不起作用

4 个答案:

答案 0 :(得分:3)

  

由于我已经使用了:operator,我该怎么做?

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

这应该没问题:

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

如果IGenericRepository是通用界面,您可能需要:

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

答案 1 :(得分:0)

使用逗号添加多个通用约束:

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

答案 2 :(得分:0)

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

您使用的:是指通用类型参数,需要是class(而不是struct),因此您可以添加额外的“:

答案 3 :(得分: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;
        }