嗯,你可以将其与反射和泛型自动化,但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,这可能为你节省很多时间。 – 2009-04-14 14:43:39