问题
Here it is:
I have two Forms and one Class, I want to pass the instance of this Class from Form1 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:
Inconsistent accessibility: parameter type 'WindowsFormsApplication1.Class1' is less accessible than method 'WindowsFormsApplication1.Form2.Form2(WindowsFormsApplication1.Class1)'
public partial class Form2 : Form
{
public Form2(Class1 c)
{
InitializeComponent();
Class1 c_1 = new Class1();
c_1 = c;
}
}
Thanks.
回答1:
You have defined your Class1 as internal:
internal class Class1
{
}
Or (the same):
class Class1
{
}
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:
Option 1: Make Class1 public
public class Class1
{ }
If you don't mind the class being accessible from any assembly ever.
Option 2: Make the constructor of your form internal
internal Form2(Class1 c)
{ }
If you don't mind that the form can never be created by any other assembly except yours.
回答2:
Class1 is an internal class of your assembly, but you are making a public method of a public class that takes Class1 as a parameter. It's like you're publically posting an ad saying "we're accepting applications for a job, but you can only get a copy of the application form if you work here already". It doesn't make any sense, so the compiler is disallowing it.
回答3:
Class1 needs to be declared as a public class i.e. public class Class1() {...} in order be used by other public classes
回答4:
Your Class1 should be public as the Form2 and its constructor has public scope. If we do not make the Class1 as public, then the access is limited. That is why the compiler displays this message.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Form2(Class1 c)
{
InitializeComponent();
Class1 c_1 = new Class1();
c_1 = c;
}
}
public class Class1
{
// Your code for Class1
}
来源:https://stackoverflow.com/questions/15256208/why-doesnt-a-constructor-accept-parameters-of-a-class-with-lower-accessibility