简体   繁体   English

使用带有类型条件的通用接口的代码契约

[英]Using Code Contracts With Generic Interface With Type Condition

I would like to add code contracts to a generic interface using an abstract class, but where the type parameter is validated. 我想使用抽象类将代码契约添加到通用接口,但是验证了type参数。

Here is an example of what I would like to do: 这是我想做的一个例子:

[ContractClass(typeof(ContractsForIRepository<,>))]
public interface IRepository<T, in TId> where T : IEntity
{
    T GetById(TId id);
    T Persist(T entity);
    void Remove(TId id);
}

[ContractClassFor(typeof(IRepository<,>))]
internal abstract class ContractsForIRepository<T, TId> : IRepository<T, TId>
{
    public T GetById(TId id)
    {
        Contract.Requires(id != null);
        return default(T);
    }

    public T Persist(T entity)
    {
        Contract.Requires(entity != null);
        return default(T);
    }

    public void Remove(TId id)
    {
        Contract.Requires(id != null);
    }
}

I can easily get it to work by dropping the condition: 我可以通过放弃条件轻松地让它工作:

  • public interface IRepository<T, in TId> where T : IEntity
  • public interface IRepository<T, in TId>

But I really want to keep this. 但我真的想保留这个。 Is it possible? 可能吗?

Okay, it is actually trivial - specify the same condition on the abstract class! 好吧,它实际上是微不足道的 - 在抽象类上指定相同的条件!

Full example below. 完整的例子如下。

[ContractClass(typeof(ContractsForIRepository<,>))]
public interface IRepository<T, in TId> where T : IEntity
{
    T GetById(TId id);
    T Persist(T entity);
    void Remove(TId id);
}

[ContractClassFor(typeof(IRepository<,>))]
internal abstract class ContractsForIRepository<T, TId> : IRepository<T, TId> where T : IEntity
{
    public T GetById(TId id)
    {
        Contract.Requires(id != null);
        return default(T);
    }

    public T Persist(T entity)
    {
        Contract.Requires(entity != null);
        return default(T);
    }

    public void Remove(TId id)
    {
        Contract.Requires(id != null);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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