【问题标题】:Interface method and parameter constraints接口方法和参数约束
【发布时间】:2014-03-06 18:20:52
【问题描述】:

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

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

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

reporter类的签名如下:

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

我希望这是有道理的。

【问题讨论】:

    标签: c# .net unity-container


    【解决方案1】:

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

    如果不是这种情况,则可能会违反约束。如果可以违反约束,那么首先就没有理由有约束。约束的目的是它们不能被违反。

    【讨论】:

      【解决方案2】:

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

      以你的情况为例:

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

      【讨论】:

        【解决方案3】:

        我已使用以下代码作为解决方案:-)

        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>());
        

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

        【讨论】:

        • 这就是我这样做的原因:-P
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多