如何在.NET 4.0中使用代码合同,而不使我的代码看起来混乱? [英] How do I use code contracts in .NET 4.0 without making my code look cluttered?

查看:139
本文介绍了如何在.NET 4.0中使用代码合同,而不使我的代码看起来混乱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用代码合约,发现它很难立即发现方法的guts。

I have started using Code Contracts and have found that it makes it difficult to immediately spot the 'guts' of a method.

采取这个:

public static void UserAddNew(string domain, string username, string displayName)
{
    Contract.Assert(!string.IsNullOrWhiteSpace(domain));
    Contract.Assert(!string.IsNullOrWhiteSpace(username));
    Contract.Assert(!string.IsNullOrWhiteSpace(displayName));

    LinqDal.User.UserAddNew(domain, username, displayName);
}

现在我试图将合同放在一个区域,可以隐藏,但是我担心我失去了一个很好的优势,能够看到的方法,看看它的期望。

Now I'm tempted to put the contracts in a region, so that they can be hidden away, but then I'm concerned that I'm losing a nice advantage of being able to glance at the method and see what it expects.

什么做你要保持合同的整洁吗?

What do you do to keep your contracts 'tidy'? Or am I just being too picky?

推荐答案

查看ContractClass和ContractClassFor属性。这允许您使用代码合同在单独的程序集中编写类。这允许您使合同可用于开发工作,不会杂乱的代码,也意味着您不必部署与实际代码的合同:

Have a look at the ContractClass and ContractClassFor attributes. This allows you to write classes with the code contracts in separate assemblies. This allows you to have the contracts available for dev work, doesn't clutter your code and also means you don't have to deploy the contracts with the live code:

合同类属性

属性的合同类

这篇关于如何在.NET 4.0中使用代码合同,而不使我的代码看起来混乱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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