C# 如何在c语言的静态函数中使用MySQL#
在静态函数中编写以下代码时,Get需要非静态错误 非静态字段、方法或属性需要对象引用 有没有可能把不能在静态函数中写入的东西包装起来,使它可以在静态函数中写入 无法编译 我使用示例代码C# 如何在c语言的静态函数中使用MySQL#,c#,mysql,C#,Mysql,在静态函数中编写以下代码时,Get需要非静态错误 非静态字段、方法或属性需要对象引用 有没有可能把不能在静态函数中写入的东西包装起来,使它可以在静态函数中写入 无法编译 我使用示例代码 private static bool OpenConnection() { try { connection.Open(); return true; }catch(Exception ex) {}
private static bool OpenConnection()
{
try
{
connection.Open();
return true;
}catch(Exception ex) {}
}
不能从静态函数访问非静态成员。非静态成员绑定到类的实例,而静态成员绑定到类本身 你的选择是:
static IDbConnection connection; //<- note the static keyword
private static bool OpenConnection()
{
try
{
connection.Open();
return true;
}catch(Exception ex) {}
}
现在您只需调用Class.OpenConnection(someConnection)代码>
维护连接对象的单个实例不是一个好主意。每次需要它时,只需创建一个新实例,打开连接、查询并释放即可。如果看不到更多的上下文,就很难给出你真正想要的确切答案。盲目猜测问题的更好解决方案:
private static IDbConnection GetConnection()
{
try
{
var connection = new WhateverConnection(yourConnectionString);
connection.Open();
return connection;
}catch(Exception ex) {}
}
使用connection对象运行查询,然后从那里将其处理掉。上下文太少,请添加静态方法的完整代码以显示完整块。很难说你在追求什么。当然,您可以将其添加到任何静态方法中。可能是因为查询和连接不是静态的。请提供异常详细信息。。太模糊了。因为连接
是非静态成员。使OpenConnection
非静态,或将connection
更改为静态(不推荐),或为静态方法提供某种方式,以从静态成员获取连接(方法)。
private static bool OpenConnection(IDbConnection connection)
{
try
{
connection.Open();
return true;
}catch(Exception ex) {}
}
private static IDbConnection GetConnection()
{
try
{
var connection = new WhateverConnection(yourConnectionString);
connection.Open();
return connection;
}catch(Exception ex) {}
}