处理数据类型转换的通用函数 [英] Generic function to handle DataType Conversion

查看:31
本文介绍了处理数据类型转换的通用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中有以下函数,我想传递一个 MySQL DataReader 值/对象.

I have the following function in C#, that I want to pass a MySQL DataReader value/object.

如果传递的对象的值是 DBNull,我需要处理它并返回该数据类型的 Null 值,例如 null int.

If the value of the object passed is a DBNull I need to handle it and return a Null value of that data type e.g null int.

否则我想转换返回值,如 Convert.ToInt32(value) 或类似的.我的功能是;

Otherwise I want to convert the returned value like Convert.ToInt32(value) or similar. My function is;

public static T ConvertFromDB<T>(object value)
{
     return value == DBNull.Value ? default(T) : (T)value;
}

我可以像

int MyInt = ConvertFromDB(oRes["FieldName"]);

但是在这种情况下,oRes["FieldName"] 的 MySQLDataReader 结果是 DBNull,这会导致异常.

However in this case the MySQLDataReader result for oRes["FieldName"] is a DBNull, which causes a exception.

任何人都可以提供任何帮助吗?我使用的是强类型列,但我遇到的问题是如果 DB 值为 DBNull,我需要返回该数据类型的 null,例如 (int)null

Can anyone offer any help on this ? I am using strongly typed columns, but the problem I have is if the DB value is DBNull, I need to return null of that data type e.g (int)null

推荐答案

也许您正在寻找 Convert.ChangeType()?

Maybe you're looking for Convert.ChangeType()?

return value == DBNull.Value ? default(T) : (T) Convert.ChangeType(value, typeof(T));

请注意,当转换失败时,您将不得不处理异常,这使得像这样的扩展方法值得怀疑.

Note that you're going to have to deal with exceptions when the conversion fails, which makes extension methods like this suspect.

也就是说,如果您正在阅读强类型列,它们应该已经是您想要的格式.为什么不直接使用 SqlDataReader.GetInt32()(或类似的)?如果是因为您想使用 SqlDataReader 的索引运算符按名称引用数据库列,也许您最好使用一组添加重载并调用 GetOrdinal 的扩展方法() 代替.有些人可能会争辩说,这是其他代码异味的表现.

That said, if you're reading strongly typed columns, they should already be in the format you want. Why not just use SqlDataReader.GetInt32() (or similar)? If it's because you want to refer to your DB columns by name using the SqlDataReader's index operator, maybe you'd be better off with a set of extension methods that add overloads and call GetOrdinal() within them instead. Some might argue that this is indicative of other code smells.

这篇关于处理数据类型转换的通用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆