如何使用DataType从数组创建数据表列?

时间:2015-11-24 09:49:56

标签: c# arrays types datatable

如何使用2D数组中的列DataType创建新的DataTable? 这是我的代码:

DataTable dtColorList = new DataTable;

string[,] values = new string[,] { {"ID","int"}, {"Name","string"}, {"ColorID","int16"} };
AddDataTableColWithType(dtColorList, values);

public static void AddDataTableColWithType(DataTable dtName, string[,] colNameAndType)
    {
        for (int i = 0; i < colNameAndType.Length / 2; i++)
        {
            dtName.Columns.Add(colName[i,0],typeof(Type.GetType(colType[i,1])));

        }
    }

Type.GetType上的错误

2 个答案:

答案 0 :(得分:0)

您必须使用Type方法编写GetType的全名,而不是使用int32方法。如果您想获得System.Int32类型,则必须指定string[,] values = new string[,] { { "ID", "System.Int32" }, { "Name", "System.String" }, { "ColorID", "System.Int16" } };

function test() {
    some_code;
}

function do_many_test() {
    var i;
    for(i=0;i<100;i++){
        test();
    }
    some_code;
    some_code;
    some_code;
}

答案 1 :(得分:0)

您可以使用这个简单的解决方案:基本思路是使用映射

public static Dictionary<string, Type> PrimitiveTypes = new Dictionary<string, Type>
      {
         {"int",typeof(int)},
         {"string",typeof(string)}
      };

    public static void Main(string[] args)
    {
        DataTable dtColorList = new DataTable();

        string[,] values = new string[,] { { "ID", "int" }, { "Name", "string" } };
        AddDataTableColWithType(dtColorList, values);

        Console.ReadLine();
    }

    public static void AddDataTableColWithType(DataTable dtName, string[,] colNameAndType)
    {
        for (int i = 0; i < colNameAndType.Length / 2; i++)
        {
            dtName.Columns.Add(colNameAndType[i, 0], PrimitiveTypes[colNameAndType[i, 1]]);
        }
    }