两个单独的班级之间如何沟通?

时间:2015-04-12 06:11:57

标签: c#

我创建了一个名为connection的独立类,我已经返回了SqlConnection,如下所示:

class connection
{
    public SqlConnection Functions()
    {
        string connetionString = null;
        SqlConnection cnn;
        Boolean flag = false;
        connetionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True";
        cnn = new SqlConnection(connetionString);

        return cnn;
    }

}

我想在另一个单独的类中使用返回的连接,但似乎错误,我编码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using WindowsFormsApplication1.deepak;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

            SqlConnection cnn ;

            connection c = new connection();
            cnn = new connection.Function();
            try
            {
                cnn.Open();
                MessageBox.Show ("Connection Open ! ");
                cnn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not open connection ! ");
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您的connection课程(我更喜欢Connection而非connection)应该可以从外部访问,因此我将其修饰符设置为public

public class Connection
{
   public SqlConnection Function()
   {
      var connetionString = /*your connection string*/
      return new SqlConnection(connetionString);
   }
}

现在,您可以按照以下方式使用它:

var conn = new Connection().Function(); //<--- you forgot the parentheses
try
{
   conn.Open();
   MessageBox.Show ("Connection Open ! ");
   conn.Close();
}
catch (Exception ex)
{
   MessageBox.Show("Can not open connection ! ");
}

答案 1 :(得分:0)

我认为您正在寻找cnn = c.Functions();而不是cnn = new connection.Function(); 我还建议您使用standard C# naming conventions并在类名称的开头使用大写字母,并为您的方法指定一个名称来描述其目的,例如GetConnection()