繁体   English   中英

C#动态创建Type数组

[英]Dynamically create an array of Type in C#

在 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 类型的空对象数组。 我很确定问题出在这里:

listTypes.Add(Type.GetType(t));

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

传入System.StringSystem.Int32而不是stringint

“string”只是 System.String 的简写。 Type.GetType不接受类型的简写符号。

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

MyFunction("System.UInt32, System.String, System.String, System.UInt32");

使用每种类型的全名,包括命名空间。 像这样:

class Program
{
    static void Main(string[] args)
    {
        var dataTypes = "System.UInt32, System.String, System.String, System.UInt32";

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

它不起作用,因为uintstring等不是 .net 类型的正式名称。 它们是System.UInt32System.String等的 C# 别名。如果您想像这样动态创建类型,则需要使用 .net 类型名称。

我知道这很旧,但这就是我破解它的方式:

private void Build_Files_DT()
    {
        String[] CLM_Header_Name_Array; Object[] Data_Type_Array;
        CLM_Header_Name_Array = new String[] { "File_Name_CLM", "Created_Date_Time_CLM", "Log_Read_CLM" };
        Data_Type_Array = new Object[] { typeof(System.String), typeof(System.DateTime), typeof(System.Boolean) };
        DT = new DataTable();
        Build_DT(DT, CLM_Header_Name_Array, Data_Type_Array);
    }

private void Build_DT(DataTable DT,  String[] CLM_Header_Name_Array, Object[] Data_Type_Array)
    {

        for (int i = 0; i < CLM_Header_Name_Array.Length; i++)
        {
            DT.Columns.Add(new DataColumn(CLM_Header_Name_Array[i], (Type)Data_Type_Array[i]));
        }
    }//Build_DT

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM