从字符串创建类型 [英] Creating Type from string

查看:141
本文介绍了从字符串创建类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的持久性库,我想动态创建类型。

不幸的是我遇到泛型类型的问题。下面的代码在运行时失败,我不知道为什么:



  var  tDict = Type.GetType(  System.Collections.Generic.Dictionary`2 []) ; 
var tDict2 = tDict.MakeGenericType( typeof int ), typeof string ));

< br $>




例外是:

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!! :)


这篇关于从字符串创建类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆