在C#中动态创建Type数组
发布时间:2020-12-15 08:07:16 所属栏目:百科 来源:网络整理
导读:在C#中,我需要能够在运行时基于逗号分隔的数据类型列表创建一个Type对象数组,这些数据类型作为字符串传递给函数.基本上,这是我想要完成的: // create array of typesType[] paramTypes = { typeof(uint),typeof(string),typeof(uint) }; 但我需要能够像这样
在C#中,我需要能够在运行时基于逗号分隔的数据类型列表创建一个Type对象数组,这些数据类型作为字符串传递给函数.基本上,这是我想要完成的:
// create array of types Type[] paramTypes = { typeof(uint),typeof(string),typeof(uint) }; 但我需要能够像这样调用我的函数: MyFunction("uint,string,uint"); 并让它根据传入的字符串动态生成数组.这是我的第一次尝试: void MyFunction(string dataTypes) { //out or in parameters of your function. char[] charSeparators = new char[] {',',' '}; string[] types = dataTypes.Split(charSeparators,stringSplitOptions.RemoveEmptyEntries); // create a list of data types for each argument List<Type> listTypes = new List<Type>(); foreach (string t in types) { listTypes.Add(Type.GetType(t)); } // convert the list to an array Type [] paramTypes = listTypes.ToArray<Type>(); } 此代码只是创建System.Type类型的null对象数组.我很确定问题出在这里: listTypes.Add(Type.GetType(t)); 关于为什么这种语法不起作用的建议? 解决方法
问题是.NET中没有uint和string类型.这些是实际
System.UInt32和
System.String类型的C#类型别名.所以你应该像这样调用你的函数:
MyFunction("System.UInt32,System.String,System.UInt32"); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |