简体   繁体   中英

C# implement interface on “where TEntity : class”

I'm relatively new to .NET and I've stumbled on this particular issue: while following a tutorial on repository pattern, the definition of the class goes like this:

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

That being said, this class is supposed to implement an interface. Since I already used the : operator, how do I do that?

I tried going public class GenericRepository<TEntity> : IGenericRepository where TEntity : class { and also public class GenericRepository<TEntity> where TEntity : class : IGenericRepository { but it doesnt work

Since I already used the : operator, how do I do that?

: isn't an operator - you're just using it in the generic type constraint. You can still specify an interface to implement.

This should be fine:

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

Or if IGenericRepository is a generic interface, you might want:

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

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

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

You'd say public class GenericRepository<TEntity> : BaseClass1, IInterface1, IInterface2, ... where TEntity : class { ...

The : you used refers to the generic type parameter needing to be a class (rather than a struct ), so you can add an additional " : ".

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

or

In my case all classes are inheriting from IdentityBaseClass thus my signature looks like:

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

Having said that what it mean is my classes, whoever wants to use GenericRepository, must inherit from IdentityBase class.

My IdentityBase class has got two properties.

 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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM