Одним из подходов будет сочетание выражений и отражений (я оставлю кеширование в качестве подробностей реализации):
// Action for a given struct that writes each field to a BinaryWriter
static Action<BinaryWriter, T> CreateWriter<T>()
{
// TODO: cache/validate T is a "simple" struct
var bw = Expression.Parameter(typeof(BinaryWriter), "bw");
var obj = Expression.Parameter(typeof(T), "value");
// I could not determine if .Net for Metro had BlockExpression or not
// and if it does not you'll need a shim that returns a dummy value
// to compose with addition or boolean operations
var body = Expression.Block(
from f in typeof(T).GetTypeInfo().DeclaredFields
select Expression.Call(
bw,
"Write",
Type.EmptyTypes, // Not a generic method
new[] { Expression.Field(obj, f.Name) }));
var action = Expression.Lambda<Action<BinaryWriter, T>>(
body,
new[] { bw, obj });
return action.Compile();
}
Используется так:
public static byte[] GetBytes<T>(T value)
{
// TODO: validation and caching as necessary
var writer = CreateWriter(value);
var memory = new MemoryStream();
writer(new BinaryWriter(memory), value);
return memory.ToArray();
}
Чтобы прочитать это обратно, это немного сложнее:
static MethodInfo[] readers = typeof(BinaryReader).GetTypeInfo()
.DeclaredMethods
.Where(m => m.Name.StartsWith("Read") && !m.GetParameters().Any())
.ToArray();
// Action for a given struct that reads each field from a BinaryReader
static Func<BinaryReader, T> CreateReader<T>()
{
// TODO: cache/validate T is a "simple" struct
var br = Expression.Parameter(typeof(BinaryReader), "br");
var info = typeof(T).GetTypeInfo();
var body = Expression.MemberInit(
Expression.New(typeof(T)),
from f in info.DeclaredFields
select Expression.Bind(
f,
Expression.Call(
br,
readers.Single(m => m.ReturnType == f.FieldType),
Type.EmptyTypes, // Not a generic method
new Expression[0]));
var function = Expression.Lambda<Func<BinaryReader, T>>(
body,
new[] { br });
return function.Compile();
}