如何使用反射和输出参数进行通用转换

时间:2012-07-04 22:37:14

标签: c# reflection

我有一个大字典(字符串,对象)。字典中的值具有不同的类型。只有在运行时,我才能在(字符串,整数)或(字符串,字符串)的字典中找到值的确切类型。在运行时,我必须将字典中的值分配给它们对应的强类型对象。这是简化的问题。 我正在尝试使用一个类型化的类来执行转换。 我有这个代码不起作用:

static void Main(string[] args)
{
    var values = new Dictionary<string, object> 
    { 
        { "123", "test"},
        {"12", 123}
    };
    var result = new Dictionary<string, object> ();

    Type dict = values.GetType();
    Type typedCast = typeof(TypedClass<>).MakeGenericType(new [] { dict });
    MethodInfo method = typedCast.GetMethod("GetTypedValue", 
        BindingFlags.Static | BindingFlags.Public, 
        null, 
        new[]
            {
                  typeof(object), 
                  typeof(object).MakeByRefType()
            },
        null);

    method.Invoke(null, new[]{values, result});
}

public class TypedClass<T>
{
    public static void GetTypedValue(object value, out object obj)
    {
        obj = (T)Convert.ChangeType(value, typeof(T));
    }
}

在GetTypedValue方法中,我看到了具有正确类型的obj值,但在此方法之外,out变量没有值。请让我知道我做错了什么。

2 个答案:

答案 0 :(得分:0)

尝试更换:

method.Invoke(null, new[]{values, result});

var invokeArgs = new[]{values, result};
method.Invoke(null, invokeArgs);
//here you can check the invokeArgs[1] for the actual result of the conversion

在任何情况下,我都不确定你为什么要将Dictionary的类型转换为另一个Dictionary,因为这就是你的代码似乎要做的......

答案 1 :(得分:0)

将out对象obj参数的类型更改为out t obj