在C#中,我需要能够根据作为字符串传递到函数的逗号分隔的数据类型列表,在运行时创建Type对象数组。基本上,这是我要完成的内容:
但是我需要能够像这样调用我的函数:
为什么这个语法不起作用?建议如下:
// create array of types
Type[] paramTypes = { typeof(uint), typeof(string), typeof(string), typeof(uint) };
但是我需要能够像这样调用我的函数:
MyFunction("uint, string, 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));
为什么这个语法不起作用?建议如下:
switch
语句或类似情况下非常有用。http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx - AniType.GetType
,忽略大小写。 - Tim Schmelter