Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用c声明全局函数或方法?_C# - Fatal编程技术网

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

C# 如何使用c声明全局函数或方法?,c#,C#,有谁能告诉我如何在c中声明一个全局函数,类似于VB.net中的一个模块? 我需要调用一个可以在我的form1、form2和form3中调用的函数 我有以下代码: using System.Data.OleDb; namespace XYZ { public static class Module { public static void dbConnection() { OleDbConnection con = new

有谁能告诉我如何在c中声明一个全局函数,类似于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”在当前上下文中不存在。

您可以创建一个静态类

namespace MyNamespace
{
    public static class MyGlobalClass
    {
        public static void MyMethod() { ... }
    }
}
然后在调用类的using部分添加名称空间以访问它。像这样:

using MyNamespace;

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

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

namespace SomeNamespace
{
    public static class SomeClass
    {
        public static string SomeMethod() 
        {
            ...
        }
    }
}
然后,在代码中,您可以使用以下方法调用它:

string x = SomeNamespace.SomeClass.SomeMethod();
或者,您可以在代码顶部设置using,只需引用它而不使用命名空间:

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

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

比如说,

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");
        }
    }
}

@kol是对的,C中没有全局函数。看看这篇文章。我将使用层,我将您的模块类重命名为TransactionModule,其外观如下:

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; }
    }
}
所有逻辑都被抽象到TransactionModule类中,然后您只需要调用方法: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);
        }
    }
}

C中没有全局函数,但您可以使方法在应用程序中全局可访问。虽然CLR支持这些方法,但C本身不支持全局函数。据我所知,如果你想调用它们,你要么用VB或者其他支持它们的语言编写逻辑,要么自己修改编译后的IL。在您的情况下,使用静态类的建议应该足够了。我认为调用名称空间GlobalNamespace或调用类GlobalClass…@kol可能会产生严重的误导,但我认为saluce试图明确地向匿名者展示类与他的问题的关系。我不知道使用static关键字,谢谢你提及此事