2014-03-06 67 views
0

我有一个接口,并希望在其中包含一个具有参数约束的类的方法。是否有可能以这种方式创建它,以至于不需要在界面删除中包含约束条件?接口方法和参数约束

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

我希望这是有道理的。

回答

2

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

如果不是这种情况,那么约束可能会被违反。如果违反约束条件,那么就没有理由首先有约束条件。 的用途的约束是他们不能违反

0

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

你的情况,例如:

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

我已经使出了下面的代码作为一种解决方案:-)

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

感谢您抽出宝贵的时间来考虑我的问题:)

+0

这正是我的答案建议你做的... – Servy

+0

这就是为什么我做到了:-P –