请说明“如何最佳”重写此代码而不使用复制粘贴。 现在我有两个处理程序与等效的lambda处理程序... 很抱歉有更多代码和糟糕的风格((
wc.DownloadStringCompleted += (sender, args) =>
{
try
{
res = (T)(object)args.Result;
var cook = Regex.Matches(wc.ResponseHeaders.ToString(), "Set\\-Cookie:\\s*([\\w\\-_\\.]+\\s*=\\s*[^;]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
foreach (Match val in cook)
cookies += val.Groups[1].Value.Trim() + "; ";
isComplited = true;
}
catch (Exception e)
{
lastError = e.InnerException.Message;
}
};
wc.UploadDataCompleted += (sender, args) =>
{
try
{
res = (T)(object)args.Result;
var cook = Regex.Matches(wc.ResponseHeaders.ToString(), "Set\\-Cookie:\\s*([\\w\\-_\\.]+\\s*=\\s*[^;]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
foreach (Match val in cook)
cookies += val.Groups[1].Value.Trim() + "; ";
isComplited = true;
}
catch (Exception e)
{
lastError = e.InnerException.Message;
}
};
答案 0 :(得分:3)
wc.DownloadStringCompleted += (sender, args) =>
{
PerformAction(sender,args);
};
wc.UploadDataCompleted += (sender, args) =>
{
PerformAction(sender,args);
};
或更短:
wc.DownloadStringCompleted += PerformAction;
wc.UploadDataCompleted += PerformAction;
创建包含此代码的新方法并运行它而不是双重代码
public void PerformAction(object sender, EventArgs args)
{
try
{
res = (T)(object)args.Result;
var cook = Regex.Matches(wc.ResponseHeaders.ToString(), "Set\\-Cookie:\\s*([\\w\\-_\\.]+\\s*=\\s*[^;]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
foreach (Match val in cook)
cookies += val.Groups[1].Value.Trim() + "; ";
isComplited = true;
}
catch (Exception e)
{
lastError = e.InnerException.Message;
}
}