简体   繁体   English

强制C#方法只传递正参数?

[英]Force a C# method to pass only positive parameters?

I want to force my method to only accept an integer parameter if it is positive . 我想强制我的方法只接受一个整数参数,如果它是积极的 If the method is passed a negative integer it should throw a compile time error. 如果该方法传递一个整数,它应该抛出编译时错误。 What is the best way to achieve this? 实现这一目标的最佳方法是什么?

Currently I am using Math.Abs(Int) inside the method, but I want the error to be at compile time. 目前我在方法中使用Math.Abs(Int) ,但我希望错误在编译时。

Just make the parameter a uint or a ushort . 只需将参数ushort uintushort That will prevent negative input at compile-time. 这将防止编译时的负面输入。 It won't prevent 0, however... I assume you're really after non-negative input rather than strictly positive input. 它不会阻止0,但是...我假设你真的是在非负输入而不是严格正输入之后。

If your method has to accept a signed parameter, then: 如果您的方法必须接受签名参数,那么:

  • You can validate the argument value, throwing an exception if it's invalid. 您可以验证参数值,如果它无效则抛出异常。 (This is a much better idea than using Math.Abs to try to "fix" invalid input.) (这比使用Math.Abs尝试“修复”无效输入好得多。)
  • You could use Code Contracts to indicate to other code that the parameter should have a non-negative value, and it will attempt to prove that everywhere you call the method, the value will be non-negative. 您可以使用代码约定向其他代码指示参数应具有非负值,并且它将尝试证明在您调用方法的任何位置时,该值将为非负值。 This won't be enforced by the C# compiler, but it can still be a build-time procedure. 这不会由C#编译器强制执行,但它仍然可以是构建时过程。

If you go with the exception approach, then you should also have a comprehensive set of unit tests around the code calling your method - and that code should validate its inputs as well, of course. 如果您使用异常方法,那么您还应该围绕调用方法的代码进行全面的单元测试 - 当然,该代码也应验证输入。

You can use Code Contracts (and link ) and do a static code analysis before compiling, then using: 您可以在编译之前使用代码约定 (和链接 )并执行静态代码分析,然后使用:

Contract.Requires( parameter >= 0 );

Static code analysis is limited, and you should NOT limit to code contracts (you should still throw runtime exceptions). 静态代码分析是有限的,您不应该限制代码契约(您仍然应该抛出运行时异常)。 It'll catch obvious things (like passing constants), but will not catch passing in negative values when they come from outside your code (read from disk, from a database, or whatever). 它会捕获明显的东西(比如传递常量),但是当它们来自代码外部时(从磁盘,数据库或其他任何东西读取),它们不会捕获负值。

That's just not possible at compile time 这在编译时是不可能的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM