How to convert a TypeCode to an actual type?

后端 未结 5 1720
一向
一向 2021-02-19 03:14

In the code below I get colType which is a code number for the type. But how would I convert that number into the actual type? Thx!!

for (int j = 0;         


        
5条回答
  •  一向
    一向 (楼主)
    2021-02-19 03:50

    I don't think there is any way to do this natively in the .NET Framework, as all the examples I've seen use a big switch statement to handle the conversion (for example: here).

    However, if you are trying to get the type as an intermediary step towards converting an object to that type, you could always use Convert.ChangeType which accepts a TypeCode as a parameter.

    double d = -1.234;
    int i = (int)Convert.ChangeType(d, TypeCode.Int32);
    

    Unfortunately, without seeing what you are trying to do I can't really say if ChangeType would be helpful or not.

    EDIT:

    To convert an int to a OleDbType, you can just cast it:

    int i = 72; //72 is the value for OleDbType.Guid
    if(Enum.IsDefined(typeof(System.Data.OleDb.OleDbType), i))
    {
        System.Data.OleDb.OleDbType dbType = (System.Data.OleDb.OleDbType)i;
        Console.WriteLine(dbType);
    }
    else
        Console.WriteLine("{0} is not defined for System.Data.OleDb.OleDbType", i);
    

提交回复
热议问题