c#的保护方法



我试图检查接收到的参数是否为0,但由于我经常这样做,我希望有一种更快的方法来检查它是否为0,而不必每次都做一个完整的if检查。

就像Guard方法一样允许我对string这样做。

下面是一个示例代码:

Guard.IsNotNullOrEmpty(myname);
Guard.IsNotNullOrEmpty(yourname);
//this works for strings and if that string is null or empty it will generate an Execption for me
if(myage == 0 )
{
throw new Exception("Your age cannot be 0");
}
//this does check if myage is 0, but it took 3 lines of code`

There is something like Guard for integers?

检查这个repo: https://github.com/Revazashvili/Forbid,有一堆方法你可以使用

我用过这个项目,你也可以在nuget上得到:https://github.com/safakgur/guard

它在一行中包含了多个需求,加上日志记录。

您可以使用Guard.IsNotDefault(source):

Guard.IsNotDefault(myage);

最新更新