我有一些数据访问层代码调用存储过程并返回各种数据类型的标量值。语法是ExecuteDecimal,ExecuteString,等我希望它是Execute<string>
或Execute<decimal>
如何让泛型能够使用需要谨慎铸造的返回值?
我尝试这个实现,我不能编译,除非我正在使用“(T)值”铸造,如果我尝试检查类型并调用一个方法来进行投射,没有这样的运气。
更新的问题 为什么我必须在转换为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 2010-06-04 18:02:08
@Andrey,欢迎来到SO =(我只是很失望,我没有去认识'精心铸造',当我读到标题时我非常兴奋=) – Marc 2010-06-04 20:13:05