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)
关于为什么这种语法不起作用的建议?
传入System.String,System.Int32而不是string和int.
"string"只是System.String的简写. Type.GetType不会接受类型的简写表示法.
问题是.NET 中没有uint和string类型。这些是实际System.UInt32和System.String类型的C#类型别名。因此,您应该这样调用函数:
MyFunction("System.UInt32, System.String, System.String, System.UInt32");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20575 次 |
| 最近记录: |