简体   繁体   中英

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

If I have a bunch of instances of FieldInfo , and I already know that their FieldType is one of the types that can be passed 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?

Eg 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);

动态关键字将在这里工作

binaryWriter.Write((dynamic)value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM