c# – 如何重構這些具有一行差異的函式
我有3個功能,其中唯一的區別是我指出的值與評論
//-- point of difference
所有這三個功能的大部分功能是一樣的. “幹”因素正在困擾我的睡眠:).我在想;這些可以容易地和可讀地併入嗎?
我以前有這樣的情況,我希望在這裡學習東西.
private string RenderRequestType(string render, NameValueCollection nvp, string prefix, string regexWild, string suffix) { string regex = prefix + regexWild + suffix; MatchCollection matches = Regex.Matches(render, regex); foreach (Match match in matches) { foreach (Capture capture in match.Captures) { string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase); //-- point of difference string value = nvp[name]; render = render.Replace(capture.Value, value); } } return render; } private string RenderSessionType(string render, HttpContext httpContext, string prefix, string regexWild, string suffix) { string regex = prefix + regexWild + suffix; MatchCollection matches = Regex.Matches(render, regex); foreach (Match match in matches) { foreach (Capture capture in match.Captures) { string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase); //-- point of difference object session = httpContext.Session[name]; string value = (session != null ? session.ToString() : ""); render = render.Replace(capture.Value, value); } } return render; } private string RenderCookieType(string render, HttpContext httpContext, string prefix, string regexWild, string suffix) { string regex = prefix + regexWild + suffix; MatchCollection matches = Regex.Matches(render, regex); foreach (Match match in matches) { foreach (Capture capture in match.Captures) { string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase); //-- point of difference HttpCookie cookie = httpContext.Request.Cookies[name]; string value = (cookie != null ? cookie.Value : ""); render = render.Replace(capture.Value, value); } } return render; }
string,string>做查詢:
private string RenderType(string render, Func<string, string> lookupFunc, string prefix, string regexWild, string suffix) { string regex = prefix + regexWild + suffix; MatchCollection matches = Regex.Matches(render, regex); foreach (Match match in matches) { foreach (Capture capture in match.Captures) { string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase); //-- point of difference string value = lookupFunc(name); render = render.Replace(capture.Value, value); } } return render; }
然後根據這個功能編寫你的功能,例如:
private string RenderRequestType(string render, NameValueCollection nvp, string prefix, string regexWild, string suffix) { return RenderType(render, name => nvp[name], prefix, regexWild, suffix); }
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/4880719/how-to-refactor-these-functions-which-have-one-line-difference