[英]Converting `Type` to `Nullable<Type>`
我正在讀取一組結果,但是遇到數據庫可能返回類型為null的類型(例如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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.