gpt4 book ai didi

c# - 有没有办法在 C# 中注释允许的值

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

我有相对经常的方法,我只希望将填充的参数作为输入。如果有人调用该方法,并且参数不正确,则应抛出错误。

有没有办法注释一个方法说:只允许某些值范围,或者它们不应该为空?

对于泛型,有类似“where”子句的限制(到目前为止还没有值)。

所以我想做而不是

private static void DoSomething(string string_in, object object_in,... ) 
{
if (null == object_in) throw new NullReferenceException("Input parameter of object is empty.");
if (String.IsNullOrEmpty(string )) throw new NullReferenceException("Input parameter string is empty.");

有点像

private static void DoSomething(string string_in, object object_in,... ) 
where string _in:!String.IsNullOrEmpty(string_in)
where object_in : object_in !=null

private static void DoSomething(string string_in != null, object object_in != null,... ) 

或者(我最喜欢哪个)

[Restriction string_in: value != null, value != empty]
[Restriction object_in: value != null]
[Restriction int_in: value inRange 3..9]
private static void DoSomething(string string _in, object object_in,... )

所以简而言之,有没有更好的方法将调用类型限制为一定数量的值,然后只需手动一遍又一遍地与某些东西进行比较?

最佳答案

代码契约为您的代码提供静态分析,因此它非常接近您的需要。作为奖励,您还可以启用运行时检查。

来自 msdn :

Code contracts provide a way to specify preconditions, postconditions, and object invariants in your code. Preconditions are requirements that must be met when entering a method or property. Postconditions describe expectations at the time the method or property code exits. Object invariants describe the expected state for a class that is in a good state.

Code contracts include classes for marking your code, a static analyzer for compile-time analysis, and a runtime analyzer. The classes for code contracts can be found in the System.Diagnostics.Contracts namespace.

The benefits of code contracts include the following:

  • Improved testing: Code contracts provide static contract verification, runtime checking, and documentation generation.

  • Automatic testing tools: You can use code contracts to generate more meaningful unit tests by filtering out meaningless test arguments that do not satisfy preconditions.

  • Static verification: The static checker can decide whether there are any contract violations without running the program. It checks for implicit contracts, such as null dereferences and array bounds, and explicit contracts.

  • Reference documentation: The documentation generator augments existing XML documentation files with contract information. There are also style sheets that can be used with Sandcastle so that the generated documentation pages have contract sections.

关于c# - 有没有办法在 C# 中注释允许的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13412092/

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