【问题标题】:C# implement interface on "where TEntity : class"C# 在“where TEntity : class”上实现接口
【发布时间】:2015-02-05 21:52:43
【问题描述】:

我对 .NET 比较陌生,偶然发现了这个特殊问题:在遵循存储库模式的教程时,类的定义如下:

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

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

我尝试过public class GenericRepository&lt;TEntity&gt; : IGenericRepository where TEntity : class {public class GenericRepository&lt;TEntity&gt; where TEntity : class : IGenericRepository {,但它不起作用

【问题讨论】:

  • 你的意思是泛型参数应该实现接口还是类型本身?
  • @Selman22 我假设是后者(“这个类应该实现一个接口”),但不清楚。

标签: c# generics interface generic-constraints


【解决方案1】:

由于我已经使用了 : 运算符,我该怎么做?

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

这应该没问题:

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

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

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

【讨论】:

  • 接受了这个答案,因为接口也是通用的,而且如何声明也令人困惑:... : IGenericRepository&lt;TEntity&gt; where...
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    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;
            }
    

    【讨论】:

      【解决方案4】:

      你会说 public class GenericRepository&lt;TEntity&gt; : BaseClass1, IInterface1, IInterface2, ... where TEntity : class { ...

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

      【讨论】:

        猜你喜欢
        • 2016-01-28
        • 1970-01-01
        • 1970-01-01
        • 2021-10-13
        • 1970-01-01
        • 1970-01-01
        • 2012-02-01
        • 2018-02-23
        相关资源
        最近更新 更多