C#泛型的问题 [英] C# generics problem

查看:86
本文介绍了C#泛型的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法(见下面)
$ b $ pre $ public T ExecuteScalar< T>(string sSql,params SqlParameter [] parameters )
{
if(!string.IsNullOrEmpty(sSql))
{
DataAccess dal = new DataAccess(ConnectionString);
DebugOutput_SQL(sSql,参数);
object value = null;
value = dal.ExecuteScalar(sSql,parameters);

if(value!= null&& value!= DBNull.Value)
return(T)value;
}
return default(T);
}

我把这称为

  int32 WorkFlowID = DataProvider.ExecuteScalar< Int32>(sSql); 

然后在return(T)行中给我一个错误值,任何建议。

解决方案

不要取消装箱值听起来像一个奇怪的错误信息。这正是它说的吗?



我的猜测是 ExecuteScalar 正在返回一个不同类型( long double 等)而不是 int 。尝试记录 value.GetType(),然后再转换为 T



正如一个旁注,这个:

  object value = null; 
value = dal.ExecuteScalar(sSql,parameters);

会更简单(IMO):

  object value = dal.ExecuteScalar(sSql,parameters); 

这里没有必要把它放在两个语句中。



编辑:只是为了澄清,它失败的原因是,当你解开一个值时,你必须解除对实际的类型,而不仅仅是一个有可用转换的类型。例如,如果您最终想要 int ,您可以这样做:

  int x =(int)(decimal)value; 

可将小数解开并转换小数转换为 int 。在这种情况下,如果可能,我只需指定正确的类型即可:)


I have a method (see below)

    public T ExecuteScalar<T>(string sSql, params SqlParameter[] parameters)
    {
        if (!string.IsNullOrEmpty(sSql))
        {
            DataAccess dal = new DataAccess(ConnectionString);
            DebugOutput_SQL(sSql, parameters);
            object value = null;
            value = dal.ExecuteScalar(sSql, parameters);

            if (value != null && value != DBNull.Value)
                return (T)value;
        }
        return default(T);
    }

and I call this

 int32 WorkFlowID = DataProvider.ExecuteScalar<Int32>(sSql);

then it give me a error "Don't unbox to value" in line "return (T)value", any suggestion for this.

解决方案

"Don't unbox to value" sounds like an odd error message. Is that exactly what it said?

My guess is that ExecuteScalar was returning a different type (long, double etc) rather than int. Try logging value.GetType() before you convert to T.

Just as a side-note, this:

object value = null;
value = dal.ExecuteScalar(sSql, parameters);

would be simpler (IMO) as:

object value = dal.ExecuteScalar(sSql, parameters);

There's no need to put it in two statements here.

EDIT: Just to clarify, the reason it's failing is that when you unbox a value, you have to unbox to the actual type, not just one which has a conversion available. For example, if you want to get an int out eventually, you could do:

int x = (int) (decimal) value;

which would unbox to decimal and then convert the decimal to an int. In this case though, I'd just specify the right type to start with if possible :)

这篇关于C#泛型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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