问题描述
这里是:
我有两个窗体和一个类,我想通过参数将此类的实例从
Form1传递到Form2 (属于第二个窗体的构造函数。)
I have two Forms and one Class, I want to pass the instance of this Class fromForm1 to Form2 through a parameter (which belongs to the second form's constructor).
public partial class Form1 : Form
{
Class1 cl = new Class1();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm_2 = new Form2(cl);
}
}
因此,我收到以下错误:
Thus, I receive the folowing error:
可访问性不一致:参数类型'WindowsFormsApplication1.Class1'的可访问性比方法'WindowsFormsApplication1.Form2.Form2(WindowsFormsApplication1.Class1)'
public partial class Form2 : Form
{
public Form2(Class1 c)
{
InitializeComponent();
Class1 c_1 = new Class1();
c_1 = c;
}
}
谢谢。
推荐答案
您已将 Class1
定义为内部
:
internal class Class1
{
}
或(相同):
class Class1
{
}
但是您有公开
方法(在本例中为构造函数),该方法接受类型为 Class1
的参数。 public
表示它在任何其他程序集中都是可见的,但是 internal
表示它仅在定义了该程序集的可见它(您的程序集)。因此,您有一个任何人都可以调用的方法,该方法接受只有您才能看到的类型的参数。那是行不通的。您在这里有两个选择:
But you have a public
method (in this case a constructor) that accepts a parameter of type Class1
. public
means that it is visible from any other assembly, but internal
means that it is only visible from the assembly that defines it (your assembly). So, you have a method that anyone can call, which accepts a parameter of a type that only you can see. That's not going to work. You have two options here:
public class Class1
{ }
如果您不介意可以从任何程序集访问该类。
If you don't mind the class being accessible from any assembly ever.
internal Form2(Class1 c)
{ }
如果您不介意除您之外的任何其他程序集都无法创建该表单。
If you don't mind that the form can never be created by any other assembly except yours.
这篇关于为什么构造函数不接受可访问性较低的类的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!