今天,我遇到了一个问题:我试图检查软件的错误,以便在出现错误时提供正确的程序行为。
我必须检查数据库中是否已经存在用户。
问题是后端没有提供errorId,因此我必须按文本检查错误。
错误显示为:
用户名已经存在!
Switch语句是这样的:
switch (error.text)
{
case "User Test already exists":
Console.WriteLine("The user already Exists"); //this is a test behaviour.
break;
default:
Console.WriteLine("I couldn't behave in any way :<");
}
可以想象到名称都是不同的(这是数据库中的唯一字段),因此case语句中的“ Test”一词应该是用户的名称。
我可以动态更改字符串吗?
似乎正则表达式可以解决问题。我基于此模式构建了此正则表达式:
The user Name already Exists!
在哪里Name
可以是任何值。正则表达式是:
(the user .* already exists)
要使用它,您将执行以下操作:
Regex.IsMatch(error.text, "(the user .* already exists)", RegexOptions.IgnoreCase)
会根据匹配结果返回true
或false
。现在,无法在开关中完成此操作,但是您可以通过多个正则表达式运行该值来确定匹配的值。您可能会考虑的一件事是扩展方法。考虑一下这一点:
public static class RegexExtensions
{
private static readonly Regex UserNameAlreadyExists = new Regex("(the user .* already exists)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static bool IsUserNameAlreadyExists(this string inputValue)
{
return UserNameAlreadyExists.IsMatch(inputValue);
}
}
这样做的用法非常好:
if (error.text.IsUserNameAlreadyExists())
{
// do something
}
扩展方法是一种很好的方法。它是完全封装的,可以使使用情况真正干净。此外,在一个地方定义正则表达式会更容易,从而将其设置为Compiled
使其更快。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句