0

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

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 变量没有值。请让我知道我做错了什么。

4

2 回答 2

0

将 out object obj 参数的类型更改为 out T obj

于 2012-07-04T23:44:17.493 回答
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,因为您的代码似乎就是这样做的...

于 2012-07-04T22:53:54.650 回答