如何声明全局函数或方法使用C#? [英] how to declare global function or method using c#?
本文介绍了如何声明全局函数或方法使用C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我如何声明在C#中一个全局函数,类似于一个模块
确实在VB.net?
我需要调用一个能在我的Form1上,窗口2和form3调用的函数。
Can anyone tell me how to declare a global function in c#, similar to what a Module
does in VB.net?
I need to call a function that can be called in my form1, form2, and 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);
}
}
}
但我有一个错误: 这个名字'骗子'没有在目前的情况下存在。
but i has an error: "The name 'con' does not exist in the current context".
推荐答案
您可以创建一个静态类。
You could create a static class.
namespace MyNamespace
{
public static class MyGlobalClass
{
public static void MyMethod() { ... }
}
}
您会再加入使用电话类部分访问它在命名空间。像这样的:
You would then add the namespace in the using
section of your calling class to access it. Like this:
using MyNamespace;
public class CallingClass
{
public void CallingMethod()
{
MyGlobalClass.MyMethod();
}
}
这篇关于如何声明全局函数或方法使用C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文