简体   繁体   English

如何自动将从FieldInfo.GetValue获得的值转换为正确的类型?

[英]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? 如果我有一堆FieldInfo实例,并且我已经知道它们的FieldType是可以传递给BinaryWriter.Write(...)的类型之一,那么如何自动将给定对象的字段传递给BinaryWriter.Write(...)没有针对一组类型测试FieldType并手动强制转换为匹配的类型?

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. 应该说,我想针对.NET 2.0进行此操作,理想情况下不使用C#3.0中没有的任何功能。

If you're using C# 4, the simplest approach would be to use dynamic typing and let that sort it out: 如果您使用的是C#4,最简单的方法是使用动态类型并将其分类:

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

That's assuming you always just want to call an overload of binaryWriter.Write . 假设您总是只想调用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: 您需要使用反射调用Write以在运行时而不是编译时找到正确的重载:

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

If you're using C# 4, you could also just use dynamic : 如果您使用的是C#4,则还可以使用dynamic

binaryWriter.Write((dynamic)value);

动态关键字将在这里工作

binaryWriter.Write((dynamic)value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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