首先,让我解释一下目前的情况:我正在从数据库中读取记录并将它们放入一个对象中以供以后使用;今天出现了一个关于数据库类型到 C# 类型转换(强制转换?)的问题。
让我们看一个例子:
namespace Test
{
using System;
using System.Data;
using System.Data.SqlClient;
public enum MyEnum
{
FirstValue = 1,
SecondValue = 2
}
public class MyObject
{
private String field_a;
private Byte field_b;
private MyEnum field_c;
public MyObject(Int32 object_id)
{
using (SqlConnection connection = new SqlConnection("connection_string"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "sql_query";
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow))
{
reader.Read();
this.field_a = reader["field_a"];
this.field_b = reader["field_b"];
this.field_c = reader["field_c"];
}
}
}
}
}
}
这(显然)失败了,因为这三个this.field_x = reader["field_x"];
调用引发了Cannot implicitly convert type 'object' to 'xxx'. An explicit conversion exists (are you missing a cast?).
编译器错误。
为了纠正这个问题,我目前知道两种方法(让我们使用这个field_b
例子):第一个是this.field_b = (Byte) reader["field_b"];
,第二个是this.field_b = Convert.ToByte(reader["field_b"]);
。
选项一的问题是DBNull
字段在强制转换失败时抛出异常(即使可空类型为 as String
),而二号的问题是它没有保留空值(Convert.ToString(DBNull)
产生 a String.Empty
),我不能使用他们也有枚举。
因此,在互联网上和 StackOverflow 上进行了几次查找之后,我想出的是:
public static class Utilities
{
public static T FromDatabase<T>(Object value) where T: IConvertible
{
if (typeof(T).IsEnum == false)
{
if (value == null || Convert.IsDBNull(value) == true)
{
return default(T);
}
else
{
return (T) Convert.ChangeType(value, typeof(T));
}
}
else
{
if (Enum.IsDefined(typeof(T), value) == false)
{
throw new ArgumentOutOfRangeException();
}
return (T) Enum.ToObject(typeof(T), value);
}
}
}
这样我应该处理每一个案件。
问题是:我错过了什么吗?我是否正在做 WOMBAT(浪费金钱、大脑和时间),因为有一种更快、更清洁的方法来做到这一点?这一切都正确吗?利润?