C#动态创建Type数组 [英] Dynamically create an array of Type in C#
问题描述
在 C# 中,我需要能够基于以逗号分隔的数据类型列表在运行时创建一个 Type 对象数组,该列表以字符串形式传递给函数.基本上,这就是我想要完成的:
In C#, I need to be able to create an array of Type objects at run-time based on a comma-delimited list of data types passed in to a function as a string. Basically, here is what I am trying to accomplish:
// create array of types
Type[] paramTypes = { typeof(uint), typeof(string), typeof(string), typeof(uint) };
但我需要能够像这样调用我的函数:
But I need to be able to call my function like this:
MyFunction("uint, string, string, uint");
并让它根据传入的字符串动态生成数组.这是我的第一次尝试:
and have it generate the array dynamically based on the string passed in. Here was my first attempt:
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 类型的空对象数组.我很确定问题出在这里:
This code simply creates an array of null objects of type System.Type. I'm pretty sure the problem lies here:
listTypes.Add(Type.GetType(t));
关于为什么这种语法不起作用的建议?
Suggestions on why this syntax does not do the trick?
推荐答案
问题是 .NET 中没有 uint
和 string
类型.这些是实际 System.UInt32 和 System.String 类型.所以你应该像这样调用你的函数:
The problem is that there are no uint
and string
types in .NET. Those are C# type aliases to the actual System.UInt32 and System.String types. So you should call your function like this:
MyFunction("System.UInt32, System.String, System.String, System.UInt32");
这篇关于C#动态创建Type数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!