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

标签 c# parameters restriction

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

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

对于泛型,有类似“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/

相关文章:

c# - 如何解决这个 Javascript/Razor 问题?

c# - MVC4 自定义表单例份验证 - 无法将 System.Web.HttpContext.Current.User 转换为 CustomPrincipal

java - 循环程序直到0(退出)(java)

javascript:获取所有对象参数

javascript - JS创建带有点击事件未接来电参数的按钮

javascript - 按键事件的 addEventListener 中的问题...仅用于限制输入字符

javascript - 使用 Intersection 库检测并对对象/路径应用限制

c# - 映射两个点列表并替换为 linq

C#/VB .Net 性能调优,生成所有可能的彩票组合

function - 条件 PowerShell 参数