开发者

How do I automatically cast a value obtained from FieldInfo.GetValue to the correct type?

开发者 https://www.devze.com 2023-04-01 14:55 出处:网络
If I have a bunch of instances of FieldInfo, and I already know that their FieldType is one of the types that can be pas开发者_JAVA百科sed to BinaryWriter.Write(...), how do I automatically pass the f

If I have a bunch of instances of FieldInfo, and I already know that their FieldType is one of the types that can be pas开发者_JAVA百科sed to BinaryWriter.Write(...), how do I automatically pass the field of a given object to the BinaryWriter.Write(...) without testing FieldType against a set of types and manually casting to the matching type?

E.g. How do I avoid having to do the following:

object value = fieldInfo.GetValue(foo);
if (fieldInfo.FieldType == typeof(int))
{
    binaryWriter.Write((int)value);
}
// followed by an `else if` for each other type.

UPDATE:

Should have said, I'd like to do this targeting .NET 2.0, ideally using nothing that isn't in C# 3.0.


If you're using C# 4, the simplest approach would be to use dynamic typing and let that sort it out:

dynamic value = fieldInfo.GetValue(foo);
binaryWriter.Write(value);

That's assuming you always just want to call an overload of binaryWriter.Write. Another alternative is to have a dictionary from the type of the value to "what to do with it":

static readonly Dictionary<Type, Action<object, BinaryWriter>> Actions = 
    new Dictionary<Type, Action<object, BinaryWriter>>
{
    { typeof(int), (value, writer) => writer.Write((int) value) },
    { typeof(string), (value, writer) => writer.Write((string) value) },
    // etc
};

Then:

object value = fieldInfo.GetValue(foo);
Actions[value.GetType()](value, binaryWriter);


You need to call Write using reflection to find the correct overload at runtime rather than compile-time:

typeof(BinaryWriter).InvokeMember(
    "Write", 
    BindingFlags.InvokeMethod, 
    null,
    binaryWriter,
    new object[] { value }
);

If you're using C# 4, you could also just use dynamic:

binaryWriter.Write((dynamic)value);


the dynamic keyword would work here

binaryWriter.Write((dynamic)value);
0

精彩评论

暂无评论...
验证码 换一张
取 消