我有一个大字典(字符串,对象)。字典中的值具有不同的类型。只有在运行时,我才能在 (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 变量没有值。请让我知道我做错了什么。