13

谁能告诉我如何在 c# 中声明一个全局函数,类似于 aModule在 VB.net 中的作用?我需要调用一个可以在我的form1、form2和form3中调用的函数。


我有这个代码:

using System.Data.OleDb;

namespace XYZ
{
    public static class Module
    {
        public static void dbConnection()
        {
            OleDbConnection con = new OleDbConnection();
            con.ConnectionString = "provider= microsoft.jet.oledb.4.0;data source=..\\dbCooperative.mdb";
            con.Open();
        }
    }
}

和表格1:

using System.Data.OleDb;
using XYZ;

namespace XYZ
{
    public partial class frmReports : Form
    {
        public frm1()
        {
            InitializeComponent();
        }

        private void frm1_Load(object sender, EventArgs e)
        {
            Module.dbConnection();
            OleDbCommand cm = new OleDbCommand("SELECT * FROM table", con);
        }
    }
}

但我有一个错误:“名称'con'在当前上下文中不存在”。

4

4 回答 4

26

如果您使用的是 C# 6.0 或更高版本,则可以使用using static.

例如,

using static ConsoleApplication.Developer;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            // Global static function, static shorthand really 
            DeveloperIsBorn(firstName: "Foo", lastname: "Bar")
                .MakesAwesomeApp()
                .Retires();
        }
    }
}

namespace ConsoleApplication
{
    class Developer
    {
        public static Developer DeveloperIsBorn(string firstName, string lastname)
        {
            return new Developer();
        }

        public Developer MakesAwesomeApp()
        {
            return this;
        }

        public Developer InsertsRecordsIntoDatabaseForLiving()
        {
            return this;
        }

        public void Retires()
        {
           // Not really
        }        
    }
}

再举一个例子:

using static System.Console;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("test");
        }
    }
}
于 2017-01-11T00:02:50.430 回答
16

您可以创建一个静态类。

namespace MyNamespace
{
    public static class MyGlobalClass
    {
        public static void MyMethod() { ... }
    }
}

using然后,您将在调用类的部分中添加命名空间以访问它。像这样:

using MyNamespace;

public class CallingClass
{
    public  void CallingMethod()
    {
        MyGlobalClass.MyMethod();
    }
}
于 2012-06-23T14:44:01.270 回答
3

您可以创建一个静态类(甚至将其包含在它自己的命名空间中,以免污染主项目命名空间),然后从任何地方调用它:

namespace SomeNamespace
{
    public static class SomeClass
    {
        public static string SomeMethod() 
        {
            ...
        }
    }
}

然后,在您的代码中,您可以使用以下命令调用它:

string x = SomeNamespace.SomeClass.SomeMethod();

using或者,您可以在代码顶部设置 a并在没有命名空间的情况下引用它:

using SomeNamespace;
...
string x = SomeClass.SomeMethod();
于 2012-06-23T14:50:14.830 回答
0

@kol 是对的,C# 中没有全局函数。看看这个帖子MSDN 帖子。我会使用图层(我将您的“模块”类重命名为“TransactionsModule”),它看起来像这样:

using System;
using System.Collections.Generic;
using System.Data.OleDb;

namespace XYZ
{
    public class TransactionsModule
    {
        public List<Person> GetPersons(string query, string connectionString)
        {
            List<Person> dbItems = new List<Person>();

            OleDbConnection conn = new OleDbConnection(connectionString);

            try 
            {
                conn.Open();
                var cmd = new OleDbCommand(query, conn);
                cmd.CommandText = query;

                using (OleDbDataReader reader = cmd.ExecuteReader())
                {
                    Person objPerson = new Person();

                    //These are the columns returned
                    objPerson.Name = Convert.ToString(myReader["Name"]);
                    objPerson.Age = Convert.ToInt32(myReader["Age"]);

                    dbItems.Add(objPerson);
                }
            } 
            catch(OleDbException ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
            return dbItems;           
        }


    }

    //This class should be in another Layer, but I placed it here since It's a quick Example
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

所有的逻辑都被抽象到TransactionsModule 类中,然后只需要调用方法:GetPersons。看一看:

using System;
using System.Collections.Generic;
using XYZ.TransactionsModule;

namespace XYZ
{
    public partial class frmReports : Form
    {      
        public frm1()
        {
            InitializeComponent();
            protected TransactionsModule moduleTran;
        }

        private void frm1_Load(object sender, EventArgs e)
        {
            //We initialize the Data Access Layer class
            moduleTran = new TransactionsModule();

            //This ConnectionString should be in your app.config
            string conString = "provider= microsoft.jet.oledb.4.0;data source=..\\dbCooperative.mdb";
            string sqlQuery = "SELECT * FROM table";

            List<Person> ItStaff = moduleTran.GetPersons(sqlQuery, conString);
        }
    }
}
于 2017-06-10T00:34:04.427 回答