不能键入'串'隐式转换为“System.Data.SqlClient.Sqlconnection” [英] Cannot implicitly convert type 'string' to 'System.Data.SqlClient.Sqlconnection'

查看:171
本文介绍了不能键入'串'隐式转换为“System.Data.SqlClient.Sqlconnection”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误:

不能隐式转换类型'串'到'System.Data.SqlClient.Sqlconnection

cannot implicitly convert type 'string' to 'System.Data.SqlClient.Sqlconnection'

这code:

SqlConnection con1 = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;

我该如何解决这个问题?我正与一个Windows应用程序。

How do I solve this problem? I am working with a Windows application.

推荐答案

这是你所需要的:

using(SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString))
{
   // do something with con1
}

注:这是比其他的答案更好,因为它包含了另一个提示:使用using关键字来保证处理您的连接对象,因此prevent连接池的问题。 :)

Note: this is better than the other answers because it includes another hint: use the using keyword to guarantee disposal of your connection object and therefore prevent connection pool problems. :)

你都拿到了拳头代替错误的原因是,你试图分配一个字符串值(ConfigurationManager.ConnectionStrings [连接]的ConnectionString),以类型的SqlConnection的变量。

The reason you were getting the error in the fist place is that you were trying to assign a string value (ConfigurationManager.ConnectionStrings["connect"].ConnectionString) to a variable of type SqlConnection.

我建议你了解更多有关的变量类型,变量铸造和类型分配在C#中,它将使编码一个更愉快的(少折腾)的经验。

I suggest you learn more about variable typing, variable casting and type assignments in C#, it will make coding a much more pleasurable (less frustrating) experience.

祝您好运!

这篇关于不能键入'串'隐式转换为“System.Data.SqlClient.Sqlconnection”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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