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

标签 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’在当前上下文中不存在”。

最佳答案

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

关于c# - 如何使用 C# 声明全局函数或方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11170383/

相关文章:

c# - 如何配置客户端? AWS Elasticsearch 请求 C#

c# - 我们在哪里使用 Debug/Trace 语句

c# - 为什么要编译?

c# - 在 C# 程序中,我试图获取应用程序的 CPU 使用率百分比,但它始终显示 100

c# - 使用 WEB API 的 EntityFramework,更新所有属性

c# - Razorpages 上的 ASP.NET Core 声明 null 处理

c# - WCF 与 SOAP HTTPS 和双工绑定(bind)

c# - 如何控制 MVVM WinRT/XAML Windows Store 应用程序中 ListView 的滚动位置?

c# - 如何按主题对电子邮件进行分组?

c# - 如何使用 Monotouch Professional 许可证在 iPad 上部署应用程序