在C#中动态创建Type数组

aco*_*ner 8 c# arrays runtime list arraylist

在C#中,我需要能够在运行时基于逗号分隔的数据类型列表创建一个Type对象数组,这些数据类型作为字符串传递给函数.基本上,这是我想要完成的:

// create array of types
Type[] paramTypes = { typeof(uint), typeof(string), typeof(string), typeof(uint) };
Run Code Online (Sandbox Code Playgroud)

但我需要能够像这样调用我的函数:

MyFunction("uint, string, string, uint");
Run Code Online (Sandbox Code Playgroud)

并让它根据传入的字符串动态生成数组.这是我的第一次尝试:

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>();

}
Run Code Online (Sandbox Code Playgroud)

此代码只是创建System.Type类型的null对象数组.我很确定问题出在这里:

listTypes.Add(Type.GetType(t));
Run Code Online (Sandbox Code Playgroud)

关于为什么这种语法不起作用的建议?

s_h*_*itt 6

传入System.String,System.Int32而不是stringint.

"string"只是System.String的简写. Type.GetType不会接受类型的简写表示法.


Dar*_*rov 5

问题是.NET 中没有uintstring类型。这些是实际System.UInt32System.String类型的C#类型别名。因此,您应该这样调用函数:

MyFunction("System.UInt32, System.String, System.String, System.UInt32");
Run Code Online (Sandbox Code Playgroud)