C# 将'Type'转换为'Nullable`
我正在读取一组结果,但遇到了这样的问题:数据库可能返回类型的可空版本,例如double或int 我想知道是否可以使用读取器中的模式信息将类型定义转换为可为空的版本。比如双倍?还是int 抛开所有SQL的东西不谈,一般来说,有没有一种方法可以进行这种类型转换?从类型对象到可空对象 typeofNullable.MakeGenericTypetype;是获取可为空类型的键C# 将'Type'转换为'Nullable`,c#,nullable,sqlcommand,C#,Nullable,Sqlcommand,我正在读取一组结果,但遇到了这样的问题:数据库可能返回类型的可空版本,例如double或int 我想知道是否可以使用读取器中的模式信息将类型定义转换为可为空的版本。比如双倍?还是int 抛开所有SQL的东西不谈,一般来说,有没有一种方法可以进行这种类型转换?从类型对象到可空对象 typeofNullable.MakeGenericTypetype;是获取可为空类型的键 for (int i = 0; i < schema.Rows.Count; i++) { var name =
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);
}
}
typeofNullable.MakeGenericTypetype;是获取可为空类型的键
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);
}
}
请使用以下功能:
public Type GetNullableTypeFrom(Type type)
{
if (!type.IsValueType || type.IsGenericType)
return type;
var nullableType = typeof(Nullable<>).MakeGenericType(type);
return nullableType;
}
请使用以下功能:
public Type GetNullableTypeFrom(Type type)
{
if (!type.IsValueType || type.IsGenericType)
return type;
var nullableType = typeof(Nullable<>).MakeGenericType(type);
return nullableType;
}
很接近,但不是很接近-我正试图从提供的模式中创建准确的类型信息。模式返回double作为类型,而实际上是double?更准确。接近,但不完全-我正在尝试从提供的模式创建准确的类型信息。模式返回double作为类型,而实际上是double?会更准确。这是正确的方法。然而,事实证明,无论如何都不能在数据表中存储可为null的类型。我想应该将它们另存为DBNull.Value。请看这篇文章:这是正确的方法。然而,事实证明,无论如何都不能在数据表中存储可为null的类型。我想应该将它们另存为DBNull.Value。见此帖: