将“Type”转换为“Nullable”
本文关键字:Type Nullable 转换 | 更新日期: 2023-09-27 18:01:29
我正在阅读一组结果,但是遇到数据库可能返回类型的可空版本的问题,例如double
或int
。
我想知道是否有可能使用来自阅读器的模式信息将类型定义转换为可空版本。如double?
或int?
?
所有的SQL的东西,有没有一种方法来做这种类型转换一般?从Type
对象到Nullable<Type>
对象
using (SqlConnection connection = new SqlConnection("... connection string here ..."))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = ".... some sql here ....";
var results = new DataTable(schema.TableName);
using (var reader = await command.ExecuteReaderAsync())
using (var schema = reader.GetSchemaTable())
{
for (int i = 0; i < schema.Rows.Count; i++)
{
var name = (string)schema.Rows[i]["ColumnName"];
var type = (Type)schema.Rows[i]["DataType"];
var allowNulls = (bool)schema.Rows[i]["AllowDBNull"];
if (allowNulls)
{
// --- How do we turn `type` into a nullable version?
// Int32 => Nullable<Int32>
// Double => Nullable<Double>
// ... etc ...
}
var column = new DataColumn(name, type);
results.Columns.Add(column);
}
}
}
请使用以下功能:
public Type GetNullableTypeFrom(Type type)
{
if (!type.IsValueType || type.IsGenericType)
return type;
var nullableType = typeof(Nullable<>).MakeGenericType(type);
return nullableType;
}
如果源类型不是可空类型,它将把你的类型转换为可空类型,否则就保持原样。
if (allowNulls)
{
type = GetNullableTypeFrom(type);
}
typeof(Nullable<>).MakeGenericType(type);
是获取可空类型
for (int i = 0; i < schema.Rows.Count; i++)
{
var name = (string)schema.Rows[i]["ColumnName"];
var allowNulls = (bool)schema.Rows[i]["AllowDBNull"];
Type type = (Type)schema.Rows[i]["DataType"];
// Add a condition to check value type. e.g. string should be non-nullable
// SQL data type should be all non-generic, skip check
if (allowNulls && type.IsValueType)
{
type = typeof(Nullable<>).MakeGenericType(type);
}
}