使用代码约定使泛型为枚举类型 [英] Using code contracts to make a generic to be of type enum

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

问题描述

几天前,我提出了一个问题,名为如何将泛型限制为枚举类型?。总结问题是下面的代码:

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 应该是 enum )。我尝试了以下代码(完整来源)。

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:

推荐答案

在文件中:

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

    }
}

代码合同部分,并选中静态检查下的所有复选框。然后我把警告级别转为高。当我重建解决方案,我收到一个警告:代码合同:不变式需要unproven: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天全站免登陆