さて、あなたは反射とジェネリックとそれを自動化することができ:(種類ごとに同じFUNCTのを書くために愚かなようだけど、IMOのオーバーロードは、より良い選択である - 。非常に多くの既存のコードのように
リフレクション/ジェネリック例 - 私は本当にこのルートをお勧めしませんが:
static void Main()
{
byte[] bytes = GetBytes(123);
}
static byte[] GetBytes<T>(T value) {
return Cache<T>.func(value);
}
static class Cache<T> {
public static readonly Func<T, byte[]> func;
static Cache() {
MethodInfo method = typeof(BitConverter)
.GetMethod("GetBytes", new Type[] { typeof(T) });
if (method == null) {
func = delegate { throw new ArgumentException(
"No GetBytes implementation for " + typeof(T).Name); };
} else {
func = (Func<T, byte[]>)Delegate.CreateDelegate(
typeof(Func<T, byte[]>), method);
}
}
}
あなたはその後、GetBytes<T>
など
を呼び出す
AddData<T>
ジェネリックメソッドでそれを混ぜます
ここではユースケースとは何ですか?手動のシリアル化コードを表示しようとしていますか?また、protobuf-netを検討すると、時間を節約できます。 –