在c#中调用.dll文件中的方法

时间:2015-03-06 09:55:15

标签: c# visual-studio

我在c#中创建了一个DLL文件,其中包含以下内容:

namespace GenerateMemo
{
class GenerateMemo
{
    public MySqlConnection connection;
    private string server;
    private string port;
    private string database;
    private string uid;
    private string password;

    public void SqlConnect(string _server, string _port, string _database, string _uid, string _password)
    {
        string connectionString;

        connectionString = "SERVER=" + _server + ";" + " PORT=" + _port + ";" + "DATABASE=" +
        _database + ";" + "UID=" + _uid + ";" + "PASSWORD=" + _password + ";";

        connection = new MySqlConnection(connectionString);
        connection.Open();
    }

    public void sqlNonQueryN(string query)
    {
        MySqlCommand cmd = new MySqlCommand(query, connection);
        cmd.ExecuteNonQuery();
        connection.Close();
    }
}

我不知道如何在文件中调用这些方法。我正在使用Visual Studio并已将其作为参考导入。请告诉我如何使用我的DLL文件。我需要在另一个项目中使用这些方法。非常感谢。 :)

2 个答案:

答案 0 :(得分:3)

首先,您需要让GenerateMemopublic在另一个程序集中使用它。现在它是internal(类的默认访问修饰符)。

然后,如果您已经将此dll添加为项目的参考 - 基本上您需要创建类的实例并将其称为方法。

var memo = new GenerateMemo();
memo.SqlConnect(....)

等等。

并确保您在计划使用它的文件中包含using GenerateMemo;命名空间。

答案 1 :(得分:0)

更具可读性:

public class GenerateMemo
{
    private MySqlConnection connection;

    private string server, database, uid, password;
    private uint port;

    public GenerateMemo(string _server, uint _port, string _database, string _uid, string _password) //constructor
    {
        server = _server;
        port = _port;
        uid = _uid;
        password = _password;
    }

    private void BuildConnection()
    {
        MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();

        builder.Server = server;
        builder.Port = port;
        builder.Database = database;
        builder.UserID = uid;
        builder.Password = password;

        connection = new MySqlConnection(builder.ConnectionString);
    }

    public void sqlNonQueryN(string query)
    {
        if (connection == null)
        {
            BuildConnection();
        }
        connection.Open();
        MySqlCommand cmd = new MySqlCommand(query, connection);
        cmd.ExecuteNonQuery();
        connection.Close();
    }
}