Created
March 3, 2017 07:30
-
-
Save y-yu/a754a698dab4a2ee4ee85c888bf32bcd to your computer and use it in GitHub Desktop.
json
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
// Jsonシリアラザ・デシリアライザを示すインターフェース | |
public interface JsonWrite<T> { | |
string ToJsonString(T obj); | |
} | |
public interface JsonRead<T> { | |
T FromJsonString(string str); | |
} | |
// 具体的なシリアラザを呼び出す拡張メソッド | |
public static class JsonWriteExtension { | |
public static string ToJsonString<S, T>(this S obj) where T: JsonWrite<S>, new() { | |
return new T().ToJsonString(obj); | |
} | |
} | |
// インスタンス定義 | |
public class IntJsonWrite: JsonWrite<int> { | |
public IntJsonWrite() { } | |
public string ToJsonString(int obj) { | |
return obj.ToString(); | |
} | |
} | |
public class ListJsonWrite<T, U>: JsonWrite<List<T>> where U: JsonWrite<T>, new() { | |
public ListJsonWrite() { } | |
public string ToJsonString(List<T> obj) { | |
return "[" + String.Join(",", obj.Select( x => new U().ToJsonString(x) )) + "]"; | |
} | |
} | |
// つかう | |
public class Test { | |
public static void Main() { | |
// ここで型を書かずに勝手に探してきて欲しい…… | |
Console.WriteLine( 1.ToJsonString<int, IntJsonWrite>() ); // string 1 | |
Console.WriteLine( new List<int>{1, 2, 3, 4}.ToJsonString<List<int>, ListJsonWrite<int, IntJsonWrite>>() ); | |
//"hoge".ToJsonString(); // compile error | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment