【发布时间】:2010-06-04 17:25:07
【问题描述】:
我有一些数据访问层代码调用存储过程并返回各种数据类型的标量值。语法是 ExecuteDecimal、ExecuteString 等。我希望它是 Execute<string> 或 Execute<decimal>
我尝试了这个实现,但我无法编译,除非我使用“(T)值”进行强制转换,如果我尝试检查类型并调用方法进行强制转换,没有这样的运气。
更新问题 为什么我必须先转换为object才能转换为T?
更新代码
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);
}
【问题讨论】:
-
嘿,我真的很担心。前三个答案(得票最高)要么有错误,要么包含不需要的代码。
-
@Andrey,欢迎来到 SO =( 我很失望我没能了解“小心选角”。当我读到标题时,我非常兴奋。=)