微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在C#中动态创建Type数组

在C#中,我需要能够在运行时基于逗号分隔的数据类型列表创建一个Type对象数组,这些数据类型作为字符串传递给函数.基本上,这是我想要完成的:
// create array of types
Type[] paramTypes = { typeof(uint),typeof(string),typeof(uint) };

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

MyFunction("uint,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));

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

解决方法

问题是.NET中没有uint和string类型.这些是实际 System.UInt32System.String类型的C#类型别名.所以你应该像这样调用你的函数
MyFunction("System.UInt32,System.String,System.UInt32");

原文地址:https://www.jb51.cc/csharp/100784.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐