代码之家  ›  专栏  ›  技术社区  ›  Ben Pretorius

接口方法和参数约束

  •  0
  • Ben Pretorius  · 技术社区  · 12 年前

    我有一个接口,希望在其中包含一个方法,该方法包含一个带有参数约束的类。是否可以以不需要在接口分解中包含约束的方式创建它?

    public interface IPlugin
    {
       void InitializeSession(MBROContext context, Reporter<TEntity, TContext> reporter);
    }
    

    TEntity是继承自IEntity的类。 TContext是继承自IDbcontext的DbContext。

    记者类签名如下:

    public class Reporter<TEntity, TContext> where TEntity : class, IEntity where TContext : IDbContext, IDisposable, new()
    {
        private IUnitOfWork uow;
        private IRepository<TEntity> entryRepository;
        private IService<TEntity> entryService;
    
        public Reporter()
        {
            this.uow = new UnitOfWork<TContext>();
            this.entryRepository = uow.GetRepository<TEntity>();
            this.entryService = new Service<TEntity>(this.uow);
        }
    
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
    

    我希望这是合理的。

    3 回复  |  直到 12 年前
        1
  •  2
  •   Servy    12 年前

    当然,您可以指定具体类型作为泛型参数(满足给定约束)。如果您不知道具体类型是什么,那么不,您就没有办法使接口通用(或者在这种情况下,一个方法可能是最好的选择),并让这些通用参数使用与 Reporter 类型

    如果不是这样的话,那么约束条件可能会被违反。如果约束条件可能被违反,那么就没有理由在第一时间设置约束条件。这个 意图 约束条件是 不能 被违反。

        2
  •  0
  •   Robban    12 年前

    简短的回答是不,你不能。但是,您可以指定实现约束的接口,以便不绑定到具体实现。

    例如,在您的案例中:

    public interface IPlugin
    {
       void InitializeSession(MBROContext context, Reporter<IEntity, IDbContext> reporter);
    }
    
        3
  •  0
  •   Ben Pretorius    12 年前

    我采用了以下代码作为解决方案:-)

    namespace USSDDomain.Core.Abstract.Contracts
    {
        public interface IPlugin
        {
            void InitializeSession<TEntity, TContext>(MBROContext context, Reporter<TEntity, TContext> reporter) where TEntity : class,IEntity where TContext : IDbContext, IDisposable, new ();
            void Execute(MBROContext context);
            string CoreCycle(MBROContext context, int stage);
            void ProcessCycle(MBROContext context, int stage, int returnStage);
            void SendResponse(MBROContext context, string xml);
            void PrepareStage(Session session);
        }
    }
    

    这允许我像这样调用基类中的方法:

    base.InitializeSession(context, new Reporter<Entry, DemoDbContext>());
    

    感谢您花时间考虑我的问题:)