【问题标题】:Converting `Type` to `Nullable<Type>`将 `Type` 转换为 `Nullable<Type>`
【发布时间】:2015-09-24 07:56:00
【问题描述】:

我正在阅读一组结果,但遇到了数据库可能返回一个类型的可为空版本的问题,例如 double 或 int。

我想知道是否可以使用来自阅读器的架构信息将类型定义转换为可为空的版本。比如double?或者int??

抛开所有 SQL 的东西,一般有没有办法进行这种类型转换?从Type 对象到Nullable&lt;Type&gt;。

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);
        }
    }
}

【问题讨论】:

  • 关闭,但不完全——我正在尝试从提供的架构中创建准确的类型信息。架构返回 double 作为类型,而真正的 double? 会更准确。

标签: c# nullable sqlcommand


【解决方案1】:

typeof(Nullable&lt;&gt;).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);
    }

}

【讨论】:

    【解决方案2】:

    请使用以下函数:

    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);
    }
    

    【讨论】:

    • 这是正确的方法。但是,事实证明,无论如何您都不能将可空类型存储在 DataTable 中。我想您应该将它们保存为DBNull.Value。看到这个帖子:stackoverflow.com/a/701261/97964
    猜你喜欢
    • 2020-07-05
    • 2020-12-27
    • 2013-11-03
    • 1970-01-01
    • 2014-08-24
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多