C# 如果等于false,则检查函数集合
我有一组方法,可以对结果进行真/假分离。 我有一个3-4个方法的集合,如果其中任何一个返回false,那么抛出一个错误 但要检查这些我能想到的就是C# 如果等于false,则检查函数集合,c#,asp.net,C#,Asp.net,我有一组方法,可以对结果进行真/假分离。 我有一个3-4个方法的集合,如果其中任何一个返回false,那么抛出一个错误 但要检查这些我能想到的就是 if(!myfunction) OR (!myOtherFunction) OR (!myOtherOtherFunction) return error 基本上堆叠在彼此的顶部。 有什么方法可以更有效地执行此操作吗?如果要报告发生错误的详细信息,可以执行以下操作: bool error = false; string message
if(!myfunction) OR (!myOtherFunction) OR (!myOtherOtherFunction)
return error
基本上堆叠在彼此的顶部。
有什么方法可以更有效地执行此操作吗?如果要报告发生错误的详细信息,可以执行以下操作:
bool error = false;
string messageError = "An erorr has occured with :";
if (!oneMethod())
{
error = true;
messageError += "\n an error occured has occured with method one";
}
if (!twoMethod())
{
error = true;
messageError += "\n an error occured has occured with method two";
}
if (error)
DisplayError(messageError);
否则,您可以在第一次发现错误时返回。
您可以将所有这些封装在一个validate方法中。如果这些方法在计算布尔值,则只应返回true或false。 如果您想实际捕获错误,请捕获错误。请参阅以了解更多原因 使用异常处理,让函数抛出异常。 然后,您周围的代码捕获(特定)异常,并适当地处理它们
try {
myfunction();
myOtherFunction();
myOtherOtherFunction();
}
catch (MyCustomException ce) {
// do something specific with a specific error
}
catch (Exception ex) {
// do something with the exception
}
如果Method1、Method2、Method3(例如)都具有相同的签名(采用相同的类型参数,返回bool),则可以:
bool Method1(YourParamType arg) { }
bool Method2(YourParamType arg) { }
bool Method3(YourParamType arg) { }
...
List<Func<YourParamType, bool>> validators = new List<Func<YourParamType, bool>>
{
Method1,
Method2,
Method3
}
...
if (!validators.All(m => m(arg)) return error;
布尔方法3(){}
List<Func<bool>> validators = new List<Func<bool>>
{
Method1,
Method2,
Method3
}
...
if (!validators.All(m => m()) return error;
List validators=新列表
{
方法1,
方法2,
方法3
}
...
如果(!validators.All(m=>m())返回错误;
同样,如果方法使用多个参数,则可以使用Func
etc
如果它们有不同的签名,您可以内联完成所有操作,但这会变得很难看:
if (!new Func<bool>[] { () => Method1(arg1), () => Method2(arg1, arg2), () => Method3() }.Any())
return error;
if(!new Func[]{()=>Method1(arg1),()=>Method2(arg1,arg2),()=>Method3()}.Any())
返回误差;
Func foo1=。。。
Func foo2=。。。
Func foo3=。。。
var foos=新列表{foo1,foo2,foo3};
bool error=foos.Any(foo=>!foo());
您的函数是否共享相同的语法?@JRoughan,它将按照OP请求返回成功而不是错误
if (!new Func<bool>[] { () => Method1(arg1), () => Method2(arg1, arg2), () => Method3() }.Any())
return error;
Func<bool> foo1 = ...
Func<bool> foo2 = ...
Func<bool> foo3 = ...
var foos = new List<Func<bool>> {foo1, foo2, foo3};
bool error = foos.Any(foo => !foo());