我想重構我的代碼,使它更優雅,更清晰,如果可以減少嵌套「if」語句。重構如果嵌套語句在C#
我的代碼「解析器」MsBuil進程的任何字符串(結果)用於檢查進程是否正確構建。
public static bool CheckMsBuildResult(string resultadoEjecucionScriptMsBuild)
{
// Build started 01/09/2010 8:54:07.
string s1 = @"Build Started \d{1,2}/\d\d/\d{4} \d{1,2}:\d\d:\d\d";
//Build started 9/1/2010 10:53:35 AM.
//Build started 9/1/2010 8:42:16 AM.
string s1Mod = @"Build Started \d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d\d:\d\d";
s1 = s1Mod;
string s11 = @"n Generar iniciada a las \d{1,2}/\d\d/\d{4} \d{1,2}:\d\d:\d\d";
// Compilaci�n iniciada a las 28/02/2011 14:56:55.
string s12 = @"Compilaci.n iniciada a las \d{1,2}/\d\d/\d{4} \d{1,2}:\d\d:\d\d";
string s2 = "Build succeeded.";
string s21 = @"Generaci.n satisfactoria\.";
string s3 = @"0 Error\(s\)";
string s31 = "0 Errores";
Regex rg = new Regex(s1, RegexOptions.Multiline | RegexOptions.IgnoreCase);
Match mt = rg.Match(resultadoEjecucionScriptMsBuild);
if (!mt.Success)
{
rg = new Regex(s11, RegexOptions.Multiline | RegexOptions.IgnoreCase);
mt = rg.Match(resultadoEjecucionScriptMsBuild);
if (!mt.Success)
{
rg = new Regex(s12, RegexOptions.Multiline | RegexOptions.IgnoreCase);
mt = rg.Match(resultadoEjecucionScriptMsBuild);
if (!mt.Success) return false;
}
}
int i = mt.Index + mt.Length;
rg = new Regex(s2, RegexOptions.Multiline | RegexOptions.IgnoreCase);
mt = rg.Match(resultadoEjecucionScriptMsBuild, i);
if (!mt.Success)
{
rg = new Regex(s21, RegexOptions.Multiline | RegexOptions.IgnoreCase);
mt = rg.Match(resultadoEjecucionScriptMsBuild);
if (!mt.Success)
{
return false;
}
}
i = mt.Index + mt.Length;
rg = new Regex(s3, RegexOptions.Multiline | RegexOptions.IgnoreCase);
mt = rg.Match(resultadoEjecucionScriptMsBuild, i);
if (!mt.Success)
{
rg = new Regex(s31, RegexOptions.Multiline | RegexOptions.IgnoreCase);
mt = rg.Match(resultadoEjecucionScriptMsBuild);
if (!mt.Success)
{
return false;
}
}
return true;
}
沒有什麼錯嵌套IFS幾級,只要你能理解發生的事情。現在你遇到的問題並不是你的ifs嵌套得太深,這是因爲非描述性變量名使得它很難理解ifs的不同嵌套中發生了什麼。 – Bazzz 2011-03-01 12:38:45