使用代码合同使通用类型为枚举类型 [英] Using code contracts to make a generic to be of type enum

查看:227
本文介绍了使用代码合同使通用类型为枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前,我问了一个题为如何约束泛型为枚举类型的问题?。总结问题是以下代码:

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#
{
}

被引入到代码合同中,我可以为这个问题编写一个编译时间警告,这是我想要的(在编译时要通知 T 应该是一个枚举)。我尝试了以下代码(完整的来源)。

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:

推荐答案

所以,我写了以下代码在一个文件中:

So, I wrote the following code in a file:

public class SomeClass<T>
{
    [ContractInvariantMethod]
    private void Invariants()
    {
        Contract.Invariant(typeof(System.Enum).IsAssignableFrom(typeof(T)));
    }

    /// <summary>Initializes a new instance of the SomeClass class.</summary>
    /// <param name="dependency"></param>
    public SomeClass()
    {

    }
}

public class SomeOtherClass
{
    public SomeOtherClass()
    {
        var myClass = new SomeClass<int>();

    }
}

从那里,我进了代码合同部分项目选项,勾选静态检查下的所有复选框。然后我将警告级别改为高。当我重建解决方案时,我收到一个警告:代码合同:不变量需要未证明:typeof(...),它们对应于类不变。

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.

从那里,我将警告级别设置回到低位,看到没有警告,ala你正在报告什么。所以,我认为将警告级别设置为高是你需要的。

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).

编辑:我发布后看到你的屏幕截图,所以我修改这个建议使用我的如果这不工作建议与类级别不变,而不是从xtor的要求调用。

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.

这篇关于使用代码合同使通用类型为枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆