动态创建的类在C#中的数组 [英] Dynamically create an array of Type in C#

查看:99
本文介绍了动态创建的类在C#中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

这code简单地创建类型的System.Type的空对象的数组。我是pretty确定问题就出在这里:

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?

推荐答案

现在的问题是,有没有 UINT 字符串类型的.NET。这些都是C#类型别名实际 System.UInt32 和< A HREF =htt​​p://msdn.microsoft.com/en-us/library/system.string.aspx相对=nofollow> 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#中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆