使用代码契约将泛型设为枚举类型
几天前,我问了一个标题为如何将泛型限制为枚举类型?的问题。总结一下这个问题是下面的代码:
class MyClass<T> where T : enum // Not possible in C#
{
}
我被介绍给代码契约,并且我可以为该问题生成一个编译时警告,这就是我想要的(在编译时被告知 T
应该)是一个枚举
)。我尝试了以下代码(完整源代码)。
class MyClass<T>
{
public MyClass()
{
Contract.Requires(typeof(System.Enum).IsAssignableFrom(typeof(T)));
}
}
它只会产生无用的运行时错误。我应该能够生成编译时警告,但我无法让它工作。谁能告诉我我做错了什么?
这是项目代码合同设置的图片:
A few days ago I asked a question titled How to constraint a generic to be of type enum?. To summarize the problem is the following code:
class MyClass<T> where T : enum // Not possible in C#
{
}
I was introduced to code contracts and that I could produce a compile time warning for the problem, which is all I want (to be informed at compile time that T
should be an enum
). I tried the follwing code (Full source).
class MyClass<T>
{
public MyClass()
{
Contract.Requires(typeof(System.Enum).IsAssignableFrom(typeof(T)));
}
}
It only produces a useless runtime error. I should be able to produce a compile time warning but I can't get it to work. Can anyone tell me what I'm doing wrong?
Here's a picture of project's Code Contracts setting:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,我在一个文件中编写了以下代码:
从那里,我进入项目选项的“代码合同”部分,并选中“静态检查”下的所有复选框。然后我将警告级别设置为“高”。当我重建解决方案时,我收到一条警告:“代码契约:不变量需要未经验证:typeof(...)”,对应于类不变量。
从那里,我将警告级别设置回低水平,发现没有警告,就像你报告的那样。因此,我认为将警告级别设置为高是您所需要的。
如果这不起作用,您可以尝试按照我所做的并将您的契约定义为类不变量(迂腐地,我建议无论如何都这样做,因为从概念上讲,这更多的是类级别不变量,而不是构造函数的结果执行)。
编辑:我在发布后看到了您的屏幕截图,因此我对此进行了修改,以建议使用我的“如果这不起作用”建议与类级别不变式,而不是需要从 xtor 调用。
So, I wrote the following code in a file:
From there, I went into the Code Contracts section of the project options and checked all checkboxes under "static checking". I then turned the warning level to "high". When I rebuilt the solution, I received a warning: "Code Contracts: invariant requires unproven: typeof(...)" that corresponded to the class invariant.
From there, I set the warning level back to low and saw that there was no warning, ala what you're reporting. So, I think that setting the warning level to high is what you need.
If that doesn't work, you might try following what I did and defining your contract as a class invariant (which, pedantically, I would suggest doing anyway because this is more of a class level invariant, conceptually, than a result of your constructor's execution).
Edit: I saw your screenshot after I posted, so I'd amend this to suggest using my "if that doesn't work" suggestion with the class level invariant instead of the requires invocation from the xtor.