如何使用c#声明全局函数或方法?

时间:2012-06-23 14:42:48

标签: c#

有谁能告诉我如何在c#中声明一个全局函数,类似于Module在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();
        }
    }
}

和form1:

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 个答案:

答案 0 :(得分:18)

如果您使用的是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");
        }
    }
}

答案 1 :(得分:14)

您可以创建一个静态类。

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

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

using MyNamespace;

public class CallingClass
{
    public  void CallingMethod()
    {
        MyGlobalClass.MyMethod();
    }
}

答案 2 :(得分:1)

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

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

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

string x = SomeNamespace.SomeClass.SomeMethod();

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

using SomeNamespace;
...
string x = SomeClass.SomeMethod();

答案 3 :(得分:0)

@kol是对的,C#中没有全局函数。看一下这篇文章MSDN post。我会使用图层(我将“模块”类重命名为“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类,然后你只需要调用Method: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);
        }
    }
}