如何在C#中从一个类调用另一个类的对象

4

我是一个新手程序员,有一个问题一直无法解决。希望您能帮我解决这个问题:
我想继承一个类:

namespace rsDeployer.Common.SQLServerCommunication         
{
    public class RSDatabaseConnectionCreator: LoggerBase
    {
        public RSProfile profile;
        public RSDatabaseConnectionCreator(RSProfile profile)
        {
            this.profile = profile;
        }

        public SqlConnection CreateConnection(RSDatabaseNames DatabaseName, bool UseWindowsAuthentication, bool testConnection = false)
        {
            var connectionString = BuildRSDatabaseConnectionString(DatabaseName, UseWindowsAuthentication);            
            if (testConnection)
            {
                return IsConnectionAvailable(connectionString) ? new SqlConnection(connectionString) : null;
            }
            return new SqlConnection(connectionString);
        }
    }
}

我希望在另一个类中调用CreateConnection()方法,并注入到其他方法中,以便能够打开连接并执行脚本。
编辑1- 我希望将其注入到的类。

        public void QueryExecution(string SQLQuery)
    {

        //here's where I would like to inject it
        SqlCommand command = new SqlCommand(SQLQuery, conn);
        var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
        file.WriteLine(command);
        file.Close();
    }

如果这个问题太愚蠢不值得回答,你可以指出我应该阅读哪些方面的内容吗?
我希望我的问题表达清晰明了。 谢谢您提前回答。

1
你应该搜索关于创建对象实例的内容。 - Berkay Yaylacı
你能展示一下你期望如何使用它吗?消费者类会是什么样子? - Juan
4个回答

2

就像这样,

public void QueryExecution(string SQLQuery)
{ 
    RSProfile profile = new RSProfile();
    RSDatabaseConnectionCreator instance = new RSDatabaseConnectionCreator(profile);
    SqlConnection conn = instance.CreateConnection(...);
    SqlCommand command = new SqlCommand(SQLQuery, conn);
    var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
    file.WriteLine(command);
    file.Close();
    conn.Close();
}

你还说你想继承这个类,这里有另一种方法,
public class RSDatabaseConnectionCreator : LoggerBase
{
    public virtual object CreateConnection() // by virtual you can override it.
    {
      return new object();
    }
}

public class AnotherClass : RSDatabaseConnectionCreator {

    public AnotherClass() {
        CreateConnection(); // by inheriting RSDatabaseConnectionCreator , you can reach public functions.
    }

    public override object CreateConnection() // or you can override it 
    {
        // here might be some user Login check
        return base.CreateConnection(); // then you open connection
    }
}

Hope helps,


也许可以使用 using conn = instance.CreateConnection();,这样连接将会自动被释放... - Martin Verjans
你说得没错,但这只是创建对象实例的示例 :) @MartinVerjans - Berkay Yaylacı

1
这是做法。之前的回答中有一个严重的错误。这个正确的做法使用了一个 "using" 将连接包围起来。
 namespace rsDeployer.Common.SQLServerCommunication         
    {
       public class ConsumerClass
       { 
           public void QueryExecution(string SQLQuery)
           {

           var profile = new RsProfile();
           var rsConnectionCreator = new RSDatabaseConnectionCreator(profile);
               using(var sqlConnection = rsConnectionCreator.CreateConnection(...Parameters here...)){
                      SqlCommand command = new SqlCommand(SQLQuery, sqlConnection );


                }
                var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
                      file.WriteLine(command);
                      file.Close();
           }
       }
    }

也许可以使用 using conn = instance.CreateConnection();,这样连接将会自动被释放... - Martin Verjans

1
希望这就是您要求的内容。
public class ClassX
{
    private RSProfile _rsprofile;
    RSDatabaseConnectionCreator _dbConnectionCreator;
    private SqlConnection _sqlConnection;

        public ClassX()
        {
           _rsProfile = xxx; //  Get the RSProfile object
           _dbConnectionCreator = new RSDatabaseConnectionCreator (_rsProfile);
           RSDatabaseNames databaseName = yyy; //  get the RSDatabaseNames 
           var useWindowsAuthentication = true; 
           var testConnection = false;

          _sqlConnection = _dbConnectionCreator.CreateConnection(databaseName,useWindowsAuthentication ,testConnection );
        }

}

非常感谢大家的努力,我真的很感激。问题已经解决了!而且我的问题语法也没出错(我太棒了:P);) - Organic Platypus

1
你可以通过构造函数将连接创建器注入到消费者类中。
public class Consumer
{
    private RSDatabaseConnectionCreator _connectionCreator;

    // Constructor injection
    public Consumer (RSDatabaseConnectionCreator connectionCreator)
    {
        _connectionCreator = connectionCreator;
    }

    public void QueryExecution(string SQLQuery)
    {
        using (var conn = _connectionCreator.CreateConnection(dbName, true, true)) {
            if (conn != null) {
                ...
            }
        }
    }
}

注意:using语句会自动关闭连接。
用法
var connectionCreator = new RSDatabaseConnectionCreator(profile);
var consumer = new Consumer(connectionCreator);
consumer.QueryExecution(sqlQuery);

如果您想在每次调用 QueryExecution 时注入连接创建器,您可以直接将其作为附加参数注入到该方法中。
public void QueryExecution(string SQLQuery, RSDatabaseConnectionCreator connectionCreator)
{
    using (var conn = connectionCreator.CreateConnection(dbName, true, true)) {
        if (conn != null) {
            ...
        }
    }
}

使用方法

var connectionCreator = new RSDatabaseConnectionCreator(profile);
var consumer = new Consumer();
consumer.QueryExecution(sqlQuery, connectionCreator);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接