我是C#的新手(如果我的问题是noobish,我道歉 - 我在教自己,所以这是一个坎坷的过程).我正在尝试开发一个winform,因为有些方法很长,我试着将它保存在几个类中.这就是我希望实现的目标:
public partial class formMainForm : Form
{
public formMainForm()
{
InitializeComponent();
}
private void UpDown1_ValueChanged(object sender, EventArgs e)
{
longCalculations.LongMethod1();
}
}
public class longCalculations
{
private void LongMethod1()
{
// Arbitrarily long code goes here
}
}
Run Code Online (Sandbox Code Playgroud)
我这样做是为了保持formMainForm课堂整洁,并能够将任何计算分成可管理的块.但是,我在非表单类中遇到使用表单控件(例如复选框,数字上下控件等)的问题.
如果我保持原样(例如CheckBox1)我得到一个名称在当前上下文错误中不存在.我四处搜索,发现这是因为该框是在不同的类中定义的.但是,如果我将其更改为formMainForm.CheckBox1,则错误现在是非静态字段,方法或属性需要对象引用.再次,我环顾四周,看来这是由于表单初始化方法不是静态的.
如果我换public formMainForm()到static formMainForm(),错误现在移动到InitializeComponent();,我不知道从哪里开始.我也尝试过对该formMainForm()方法进行实例化,但是没有做任何事情(我试图使用的代码如下.我发现它在这个网站的某个地方作为类似问题的答案).
private void formLoader(object sender, EventArgs e)
{
shadowrunMainForm runForm = new shadowrunMainForm();
runForm.Show();
}
Run Code Online (Sandbox Code Playgroud)
如何在其他类中使用formcontrol名称?
PS这是我在这里发表的第一篇文章 - 如果我错过了这个已被问到某个地方的问题,我感到非常抱歉.我做了搜索,但我找不到我想要的东西.
似乎我没有说清楚 - 这只是代码的一个例子,我的问题是第二类,而不是第一类.我现在已经将代码简化为:
public partial class formMainForm : Form
{
public formMainForm()
{
InitializeComponent();
}
}
public class longCalculations
{
private void LongMethod1()
{
List<CheckBox> listOfBoxes = new List<CheckBox>();
listOfBoxes.Add(CheckBox1);
// The code displays an "object reference is required for the non-static field, method or property" error at this stage. Changing the "CheckBox1" to formMainForm.CheckBox1 doesn't help
// Arbitrarily long code goes here
}
}
Run Code Online (Sandbox Code Playgroud)
LongMethod1放置在formMainForm部分类中时效果非常好.将其移动到其他表单使其无法从这些复选框中获取数据.
我相信这行longCalculations.LongMethod1();是抛出错误,因为你试图访问一个实例方法,好像它是一个static方法,并且它被定义为private在类外无法访问的方法.您需要创建的实例longCalculations访问任何的前类的成员或方法(S)和标记方法public类似
private void UpDown1_ValueChanged(object sender, EventArgs e)
{
longCalculations ln = new longCalculations();
ln.LongMethod1();
}
public class longCalculations
{
public void LongMethod1()
{
// Arbitrarily long code goes here
}
}
Run Code Online (Sandbox Code Playgroud)
(或者)如果你真的希望它是一个static方法,那么使用static修饰符相应地定义
public class longCalculations
{
public static void LongMethod1()
{
// Arbitrarily long code goes here
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以像你尝试的方式一样调用它