如何将值转换为作为参数传递的类型 [英] How to convert a value to a type that is passed as a parameter

查看:50
本文介绍了如何将值转换为作为参数传递的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它将执行聚合函数(即COUNT(),MIN(),MAX())

I have a function that will execute aggregated function (ie. COUNT(),MIN(), MAX())

有时我想返回 int,double,date,datetime....

我在尝试转换返回值时遇到问题

I'm having an issue trying to convert the return value

以下一行给我一个错误 value = Convert.ChangeType(vv,typeof(T));

the following line is giving me an error value = Convert.ChangeType(vv, typeof(T) );

这是错误

无法将类型'object'隐式转换为'T'.存在显式转换(您是否缺少演员表?)

Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?)

这是我的方法

public T getValue<T>(string query, List<MySqlParameter> pars)
{
    T value;
    using (var conn = new MySqlConnection(conn_string))
    using (var cmd = new MySqlCommand(query, conn))
    {
        if (pars != null)
        {
            foreach (MySqlParameter p in pars)
            {
                cmd.Parameters.Add(p);
            }
        }

        conn.Open();
        try
        {
            object vv = (T)cmd.ExecuteScalar();

            if (vv != null)
            {
                value = Convert.ChangeType(vv, typeof(T) );
            }
        } catch(Exception ex){

            Common.Alert(ex.ToString(), "SQL Error");
            value = default(T);

        } finally {
            conn.Close();
        }
    }

    return value;
}

当我使用此方法时,我会使用

And when I use this method I use this

int cnt = db.getValue<int>(query, params);

推荐答案

您的代码没有多大意义.首先,您将其转换为 T ,然后将其转换为 T 吗?转换是没有用的.我认为值得指出的是,您遇到的特定错误(无法将类型'object'隐式转换为'T'.")是因为

Your code doesn't make a lot of sense. First you cast to T, then if it's not null, you convert it to T? The conversion is useless. I think it's worth pointing out that the particular error you're getting ("Cannot implicitly convert type 'object' to 'T'.") is because Convert.ChangeType returns an object, so it's often casted immediately after calling:

value = (T)Convert.ChangeType(v, typeof(T));

您可能需要这样做:

object rawValue = cmd.ExecuteScalar();

value = (T)Convert.ChangeType(rawValue, typeof(T));

请注意,如果 rawValue null ,并且 T 是值类型( struct ,例如int ),此(部分)代码将引发异常.这可能比默默地将值设为 default(T)更好.

Note that if rawValue is null and T is a value type (struct, e.g. int), this (portion of) code will throw an exception. This is probably better than silently letting the value be default(T).

这篇关于如何将值转换为作为参数传递的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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