Created
April 20, 2012 23:55
-
-
Save ledsun/2432731 to your computer and use it in GitHub Desktop.
C#2.0からC#3.0にリファクタリングした例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// クエリストリング生成用辞書 | |
/// </summary> | |
class QueryParams : Dictionary<string, string> | |
{ | |
/// <summary> | |
/// 設定したパラメータからクエリストリング文字列を作ります。 | |
/// 次の形式で文字列を返します。key1=val1&key2=val2 | |
/// valにURLで使えない文字列が入っていた場合、そのままResponse.Redirectに入れるとURLエンコードされます。 | |
/// valの値はすべてURLエンコードして返します。 | |
/// </summary> | |
public string QueryString | |
{ | |
get | |
{ | |
var s = ""; | |
foreach (string key in Keys) | |
{ | |
if (!string.IsNullOrEmpty(s)) | |
s += "&"; | |
s += key + "=" + HttpUtility.UrlEncode(this[key]); | |
} | |
return s; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class QueryParams | |
{ | |
/// <summary> | |
/// 設定したパラメータからクエリストリング文字列を作ります。 | |
/// 次の形式で文字列を返します。key1=val1&key2=val2 | |
/// valにURLで使えない文字列が入っていた場合、そのままResponse.Redirectに入れるとURLエンコードされます。 | |
/// valの値はすべてURLエンコードして返します。 | |
/// </summary> | |
public static string MakeQueryString(this Dictionary<string, string> dic) | |
{ | |
return string.Join( | |
"&", | |
dic.Select(kv => kv.Key + "=" + HttpUtility.UrlEncode(kv.Value)) | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestMethod] | |
public void クエリストリングを生成します() | |
{ | |
var q = new QueryParams(); | |
q["hoge"] = "fuga"; | |
Assert.AreEqual<string>("hoge=fuga", q.QueryString); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestMethod] | |
public void クエリストリングを生成します() | |
{ | |
var q = new Dictionary<string, string>(); | |
q["hoge"] = "fuga"; | |
Assert.AreEqual<string>("hoge=fuga", q.MakeQueryString()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment