如何使用c#声明全局函数或方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11170383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to declare global function or method using c#?
提问by anonymizer
Can anyone tell me how to declare a global function in c#, similar to what a Moduledoes in VB.net?
I need to call a function that can be called in my form1, form2, and form3.
谁能告诉我如何在 c# 中声明一个全局函数,类似于ModuleVB.net 中的 a ?我需要调用一个可以在我的form1、form2和form3中调用的函数。
i have this code :
我有这个代码:
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();
}
}
}
and form1:
和形式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);
}
}
}
but i has an error: "The name 'con' does not exist in the current context".
但我有一个错误:“当前上下文中不存在名称'con'”。
回答by Kevin Aenmey
You could create a static class.
您可以创建一个静态类。
namespace MyNamespace
{
public static class MyGlobalClass
{
public static void MyMethod() { ... }
}
}
You would then add the namespace in the usingsection of your calling class to access it. Like this:
然后,您将在using调用类的部分中添加命名空间以访问它。像这样:
using MyNamespace;
public class CallingClass
{
public void CallingMethod()
{
MyGlobalClass.MyMethod();
}
}
回答by saluce
You can create a static class (even enclose it in it's own namespace so as not to pollute the main project namespace), then call it from anywhere:
您可以创建一个静态类(甚至将它包含在它自己的命名空间中,以免污染主项目命名空间),然后从任何地方调用它:
namespace SomeNamespace
{
public static class SomeClass
{
public static string SomeMethod()
{
...
}
}
}
Then, in your code, you can call it using:
然后,在您的代码中,您可以使用以下方法调用它:
string x = SomeNamespace.SomeClass.SomeMethod();
Or, you can set up a usingat the top of the code and just reference it without the namespace:
或者,您可以using在代码顶部设置 a并且只引用它而不带命名空间:
using SomeNamespace;
...
string x = SomeClass.SomeMethod();
回答by Alex Nolasco
If you're using C# 6.0 or later, you could use using static.
如果您使用的是 C# 6.0 或更高版本,则可以使用using static.
For example,
例如,
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
}
}
}
One more example:
再举一个例子:
using static System.Console;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
WriteLine("test");
}
}
}
回答by Pastor Cortes
@kol is right, there are NO global functions in C#. Take a look at this post MSDN post. I would use layers (I renamed your "Module" class to "TransactionsModule") and It would look like this:
@kol 是对的,C# 中没有全局函数。看看这篇MSDN 帖子。我会使用层(我将你的“模块”类重命名为“事务模块”),它看起来像这样:
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; }
}
}
All the logic was abstracted to the TransactionsModule class, then you only need to call the Method: GetPersons. Take a look:
所有的逻辑都抽象到了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);
}
}
}

