代码契约:ContractClassFor 处理通用抽象类时?
所以,我这里有一个小问题。
假设我有:
public class Repository<TEntity>
where TEntity : class
{
public abstract void Add(TEntity entity);
// ...and so on...
}
现在我想定义一个契约类,如下所示:
public class RepositoryContracts<TEntity> : Repository<TEntity>
where TEntity : class
{
public void Add(TEntity entity)
{
Contract.Requires(entity != null);
}
// ...etc...
}
现在,我必须使用 ContractClassAttribute 和 ContractClassForAttribute 来标记这些类。问题是,这行不通:
[ContractClassFor(typeof(Repository<TEntity>))] // what is TEntity?! error!
所以,问题归结为:当它们是通用的时,如何使用这些属性将这两个类链接在一起?
So, I have a little problem here.
Suppose I have:
public class Repository<TEntity>
where TEntity : class
{
public abstract void Add(TEntity entity);
// ...and so on...
}
And now I want to define a contract class, like so:
public class RepositoryContracts<TEntity> : Repository<TEntity>
where TEntity : class
{
public void Add(TEntity entity)
{
Contract.Requires(entity != null);
}
// ...etc...
}
Now, I'd have to mark these classes with ContractClassAttribute and ContractClassForAttribute. Problem being, this won't work:
[ContractClassFor(typeof(Repository<TEntity>))] // what is TEntity?! error!
So, the question boils down to: How do I link these two classes together using those attributes, when they're generic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明,这是
typeof(Repository<>) 语法似乎对我不起作用,但事实证明, typeof(Repository<,>) 可以解决问题,因为有两个类型参数。
结束问题,并向 前一个。
Turns out this is a duplicate of this question, kinda.
The typeof(Repository<>) syntax didn't seem to work for me, but turns out, typeof(Repository<,>) does the trick, since there are two type parameters.
Closing the question, and adding a comment to the previous one.