gpt4 book ai didi

c# - 代码契约(Contract)不检查空条件。为什么?

转载 作者:行者123 更新时间:2023-11-30 17:11:43 29 4
gpt4 key购买 nike

为什么 .NET Contracts 不提示这段代码?

private static User GetUser()
{
var sFirstName = Console.ReadLine();
var sLastName = Console.ReadLine();
if (sLastName == "NULL")
{
return null;
}
else
{
return new User(sLastName, sFirstName);
}
}
public static int Main(string[] args)
{
var oUser = GetUser();
DisplayUser(oUser);
Console.ReadLine();
return 0;
}
private static void DisplayUser(User user)
{
Contract.Requires(user != null);
Console.WriteLine(user.ToString());
}

GetUser 可以返回 null,但契约(Contract)从未规定我必须在将返回值传递给 DisplayUser 之前检查返回值。为什么?


AutoAnswer:代码契约配置中存在警告级别。我应该把它从低到高。

最佳答案

根据 this msdn页面,如果您没有在 Visual Studio 中安装正确的插件,契约(Contract)将不会被执行。你安装那个插件了吗?

You must install a Visual Studio add-in to enforce contracts. The Code Contracts Premium Edition add-in lets you specify static and run-time checking of code contracts on the project Properties page. If you do not enable run-time checking, contracts such as the Contract.Ensures method will not throw exceptions during run time if a contract is violated. The Visual Studio add-in does not ship with Visual Studio 2010 or the Windows SDK.

关于c# - 代码契约(Contract)不检查空条件。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11225964/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com