本文介绍了从字符串创建类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于我的持久性库,我想动态创建类型。 不幸的是我遇到泛型类型的问题。下面的代码在运行时失败,我不知道为什么:
var tDict = Type.GetType( System.Collections.Generic.Dictionary`2 []) ; var tDict2 = tDict.MakeGenericType( typeof ( int ), typeof ( string ));例外是:
InvalidOperationException:其他信息:System.Collections.Generic.Dictionary`2 [TKey,TValue] []不是GenericTypeDefinition。 MakeGenericType只能在Type.IsGenericTypeDefinition为true的类型上调用。
解决方案
以下代码可以解决问题: 私人 void test() {类型tDict = Type.GetType( System.Collections.Generic.Dictionary`2 [System.Int32,System.String])。GetGenericTypeDefinition(); var tDict3 = tDict.MakeGenericType( typeof ( string ), typeof ( string )); var tDict2 = tDict.MakeGenericType( typeof ( int ), typeof ( string )); }
已解决! var tDict = Type.GetType( System.Collections.Generic.Dictionary`2);
有效!! :)
For my persistence library I would like to create type dynamically. Unfortunately I have a problem with generic types. The code below fails at runtime and I have no clue why:
var tDict = Type.GetType("System.Collections.Generic.Dictionary`2[]"); var tDict2 = tDict.MakeGenericType(typeof(int), typeof(string));The exception is:
InvalidOperationException:Additional information: System.Collections.Generic.Dictionary`2[TKey,TValue][] is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.
解决方案 The following code makes the trick: private void test() { Type tDict = Type.GetType("System.Collections.Generic.Dictionary`2[System.Int32, System.String]").GetGenericTypeDefinition(); var tDict3 = tDict.MakeGenericType(typeof(string), typeof(string)); var tDict2 = tDict.MakeGenericType(typeof(int), typeof(string)); }Solved! var tDict = Type.GetType("System.Collections.Generic.Dictionary`2");works!! :)
更多推荐
从字符串创建类型
发布评论