如何使泛型与需要精心铸造的返回值一起工作? [英] How do I get generics to work with return values that require careful casting?
问题描述
我有一些数据访问层代码调用存储过程并返回各种数据类型的标量值。语法是ExecuteDecimal,ExecuteString等。我希望它是 Execute< string>
或执行< decimal>
我尝试这个实现,我无法编译,除非我在使用(T)值进行投射,如果我尝试检查类型并调用方法要做铸造,没有这样的运气。
已更新的问题
为什么在转换为T之前必须转换为对象?
更新后的代码
internal T执行< T>(字符串storedProcName,哈希表参数)
{
//下一行做编译(感谢来自答案的建议!)
if(typeof(T)== typeof(string) )
return(T)(object)ExecuteScalar(storedProcName,parameters).ToString();
else if(typeof(T)== typeof(int))
return(T)(object)Convert.ToInt32(ExecuteScalar(storedProcName,parameters));
//下一行编译,但不是所有装在对象中的东西都可以
//直接转换为T(esp db返回的值可能包含DbNull.Value等)
return (T)ExecuteScalar(storedProcName,parameters);
试试这个:
var result = ExecuteScalar(storedProcName,parameters);
if(Convert.IsDBNull(result))
return default(T);
if(result是T)//只是取消箱
返回(T)结果;
else //转换
return(T)Convert.ChangeType(result,typeof(T));
更新:固定DBNull处理
I've got some data access layer code calls a stored proc and returns scalar values of various datatypes. The syntax is ExecuteDecimal, ExecuteString, etc. I want it to be Execute<string>
or Execute<decimal>
I try this implementation and I can't compile, unless I'm doing casting using "(T) value", if I try to check the type and call a method to do the casting, no such luck.
UPDATED question Why do I have to convert to object before converting to T?
UPDATED code
internal T Execute<T>(string storedProcName, Hashtable parameters)
{
//Next lines do compile (thanks to suggestions from answers!)
if (typeof(T) == typeof(string))
return (T) (object) ExecuteScalar(storedProcName, parameters).ToString();
else if (typeof(T) == typeof(int))
return (T)(object) Convert.ToInt32(ExecuteScalar(storedProcName, parameters));
//Next line compiles, but not all things boxed in an object can
//be converted straight to type T (esp db return values that might contain DbNull.Value, etc)
return (T)ExecuteScalar(storedProcName, parameters);
}
Try this:
var result = ExecuteScalar(storedProcName, parameters);
if(Convert.IsDBNull(result))
return default(T);
if(result is T) // just unbox
return (T)result;
else // convert
return (T)Convert.ChangeType(result, typeof(T));
Updated: fixed DBNull handling
这篇关于如何使泛型与需要精心铸造的返回值一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!