从字符串创建类型

编程入门 行业动态 更新时间:2024-10-27 11:23:48
本文介绍了从字符串创建类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于我的持久性库,我想动态创建类型。 不幸的是我遇到泛型类型的问题。下面的代码在运行时失败,我不知道为什么:

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

更多推荐

从字符串创建类型

本文发布于:2023-10-28 02:03:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535178.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!