如何从另一个类访问一个类中的对象。 [英] How do I access object in one class from another class.

查看:76
本文介绍了如何从另一个类访问一个类中的对象。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Here is my database connection class.I want to access 'oracleCommand' object reference from another class.

<pre>public class DBConnection
        { 
            //public OracleCommand oracleCommand;
            public string cmd = "";
            public void makeConnection()
            {
                //Opening connection
                string connectionString = "XXXX";
                OracleConnection con = new OracleConnection();
                con.ConnectionString = connectionString;
                con.Open();
                OracleCommand oracleCommand = con.CreateCommand();
                cmd = oracleCommand.CommandText;
                //Clossing resources
                con.Close();
                oracleCommand.Dispose();
            }



然后我想执行以下查询。




Then I want to execute the following query.

dbConnection.cmd = "SELECT COUNT(JOB_ID) FROM EmployeeTable WHERE STATUS='Pending'";
                OracleDataReader Reader = dbConnection.oracleCommand.ExecuteReader();
                Reader.Read();



但调试时dbConnection.oracleCommand.ExecuteReader()没有命中。有没有人有想法?



我尝试过:



我创建了'


But 'dbConnection.oracleCommand.ExecuteReader()' does not hit when debugging. Does anyone has an idea?

What I have tried:

I created '

public OracleCommand oracleCommand;

对象并尝试传递。但它没有执行。

object and tried to pass.But it does not execute.

推荐答案

oracleCommand只存在于makeConnection中,所以只有该函数内的代码才能访问它,所以我不明白你的代码是如何编译的。如果你想建立一个连接,你需要写一个像



oracleCommand only exists inside makeConnection so only code inside that function can access it, so I don't understand how your code even compiles. If you want to make a connection available you'll need to write a function like

public static OracleCommand GetConnection()
{
    string connectionString = "XXXX";
    OracleConnection con = new OracleConnection();
    con.ConnectionString = connectionString;
    con.Open();
    OracleCommand oracleCommand = con.CreateCommand();
    return oracleCommand;
}





无论如何都是这样的,你会称之为





Something like that anyway, and you'd call it like

var c = DBConnection.GetConnection();





注意方法声明中的静态。



调用代码需要处理资源的清理,这就是为什么这样的代码通常是个坏主意。只需在任何需要它的代码中创建命令。



Note the "static" on the method declaration.

The calling code would need to handle the cleaning up of the resources which is why code like this is usually a bad idea. Just create the command in any code that needs it.


这篇关于如何从另一个类访问一个类中的对象。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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