.NET 4.0 中开箱即用的代码协定
我真的很想尝试 Visual Studio 2010 中的新代码契约,但我不想安装 Visual Studio 的其他扩展(因为我的代码与同事共享)。 现在,当面向 .NET 4.0 时,我可以使用新的 System.Diagnostics.Contracts 命名空间,但我还没有让它执行任何操作。
例如,使用
static void Main(string[] args)
{
Greet(null);
Console.ReadLine();
}
private static void Greet(string name)
{
Contract.Requires(name != null);
Console.Out.WriteLine("Hello {0}", name);
}
程序编译并运行(显示“Hello”),没有任何类型的警告。如果我尝试使用 Contract.Requires
,我会收到一条消息,告诉我必须使用重写器,无论 name 的值如何。 谷歌告诉我,当我安装 Code Contracts premium 时我可以获得任何魔法,但是如果我不安装,这个命名空间的目的是什么?除了开箱即用的详细注释之外,我还可以将代码契约用于其他用途吗?
I'd really like to try out the new Code Contract in Visual Studio 2010, but I don't want to install additional extensions to Visual Studio (since my code in shared with my coworkers).
Now, when targeting .NET 4.0 I can use the new System.Diagnostics.Contracts namespace, but I don't get it to do anything yet.
For example, using
static void Main(string[] args)
{
Greet(null);
Console.ReadLine();
}
private static void Greet(string name)
{
Contract.Requires(name != null);
Console.Out.WriteLine("Hello {0}", name);
}
The program compiles and runs (displaying "Hello ") without warning of any kind. If I try to use Contract.Requires<ArgumentNullException>(name != null)
, I get a message telling me that I must use the rewriter, regardless of the value of name.
Google tells me, that I can get any kind of magic when I install Code Contracts premium, but what is the purpose of this namespace when I don't? Can I use Code Contracts for something other than elaborate comments out of the box?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,如果您定义 CONTRACTS_FULL 预处理器符号,则各种
Contract.*
方法将因重写器未运行而失败(根据注释)。除非您定义预处理器符号,否则它们将在编译时被忽略。在框架中包含最少的代码契约类的目的是,在部署代码时无需安装额外的软件 - 但您确实需要安装额外的软件工具来进行构建时后处理。
Well, if you define the
CONTRACTS_FULL
preprocessor symbol then the variousContract.*
methods will fail due to the rewriter not being run (as per comments). Unless you define the preprocessor symbol, they'll be ignored at compile-time.The point of including the bare minimum Code Contracts classes in the framework is so that no extra software has to be installed when deploying the code - but you do need to install the extra tools in order to do the build-time post-processing.
我想答案是您反对安装扩展。开箱即用的合同意味着您可以使用您希望的合同的所有用途,并且您的同事将能够在不安装任何扩展的情况下编译代码。
然后,您可以继续安装扩展并从合同中获得真正的好处,而不会对您的同事提出任何新要求
I guess the answer is in your objections to installing extensions. Having the contracts out of the box means that you can have all the use of the contracts you wish to an your coworkers will be able to compile the code without any extensions installed.
You can then go ahead and install the extension and get the real benefits from the contracts without imposing any new requirements on your coworkers