如何使用泛型来处理需要仔细投射的返回值?

Mat*_*tin 7 .net c# generics casting

我有一些数据访问层代码调用存储过程并返回各种数据类型的标量值.语法是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);
}
Run Code Online (Sandbox Code Playgroud)

max*_*max 11

试试这个:

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));
Run Code Online (Sandbox Code Playgroud)

更新:修复了DBNull处理