我需要根据DataTable中DataColumns的类型来格式化输出。
具体而言,我需要将内置的原始类型(int、string、decimal、DateTime等)映射到:
- SomeEnum.Numeric
- SomeEnum.Bool
- SomeEnum.DateTime
- SomeEnum.String
- SomeEnum.Unknown
- SomeEnum.Null
我该如何做?
如果内置的 TypeCode
枚举符合您的需求,则可以直接读取 DataColumn
的 DataType
属性,然后调用 GetTypeCode
。
TypeCode yourTypeCode = Type.GetTypeCode(yourDataColumn.DataType);
switch (yourTypeCode)
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
Console.WriteLine("Numeric");
break;
case TypeCode.Boolean:
Console.WriteLine("Bool");
break;
case TypeCode.DateTime:
Console.WriteLine("DateTime");
break;
case TypeCode.String:
Console.WriteLine("String");
break;
case TypeCode.Empty:
Console.WriteLine("Null");
break;
default: // TypeCode.DBNull, TypeCode.Char and TypeCode.Object
Console.WriteLine("Unknown");
break;
}
TypeCode
不能满足你的需求,那么你可以按照 John's answer 中所述,将列类型简单地转换为自定义的枚举类型。你可以使用:
var types = new Dictionary<Type, SomeEnum>()
{
{ typeof(int), SomeEnum.Numeric },
{ typeof(long), SomeEnum.Numeric },
{ typeof(string), SomeEnum.String },
...
};
Func<Type, object, SomeEnum> getTypeEnum = (type, obj) =>
{
var result = types.ContainsKey(type)
? types[type]
: SomeEnum.Unknown;
if (obj == null || obj is DBNull)
{
result = SomeEnum.Null;
}
return result;
};
...
var e = getTypeEnum(col.DataType, row[col]);