gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:48:58 25 4
gpt4 key购买 nike

谁能告诉我如何在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com