将`Type`转换为`Nullable <Type>`

joc*_*ull 1 c# nullable sqlcommand

我正在阅读一组结果,但遇到数据库可能返回类型的可空版本的问题,例如a doubleint.

我想知道是否可以使用读者的架构信息将类型定义转换为可空版本.如?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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

con*_*e g 5

请使用以下功能:

public Type GetNullableTypeFrom(Type type)
{
    if (!type.IsValueType || type.IsGenericType)
        return type;

    var nullableType = typeof(Nullable<>).MakeGenericType(type);

    return nullableType;
}
Run Code Online (Sandbox Code Playgroud)

如果源类型不是,它会将您的类型转换为可为空的类型,否则只是保持原样.

if (allowNulls)
{
    type = GetNullableTypeFrom(type);
}
Run Code Online (Sandbox Code Playgroud)