简体   繁体   English

C#-无法访问其他类的公共功能

[英]C# - Can't access public function from different class

I'm starting with C# and I got a problem. 我从C#开始,但遇到了问题。

I created a "Windows Form Application" project. 我创建了一个“ Windows Form Application”项目。

I have a form class named form1 and I added a UserControl class named usercontrol1. 我有一个名为form1的表单类,并且添加了一个名为usercontrol1的UserControl类。 In usercontrol1, I have a public function named test which returns 123. 在usercontrol1中,我有一个名为test的公共函数,该函数返回123。

For some reason I can't do this: 由于某些原因,我无法执行此操作:

private void Form1_Load(object sender, EventArgs e)
{
 UserControl usercontroltest = new usercontrol1();
 usercontroltest.test();
} 

The error I get is "user control does not contain a definition for" 我得到的错误是“用户控件不包含定义”

This is because you've declared your variable to be of type UserControl . 这是因为您已将变量声明为UserControl类型。 That means the compiler will only let you use members declared in UserControl and the classes it inherits from. 这意味着编译器将只允许您使用UserControl声明的成员及其继承的类。 The actual object is still of type usercontrol1 at execution time, but the compiler only cares about the compile-time type of the variable you're trying to use to call the method. 实际的对象仍然类型usercontrol1的执行时间,但是编译器只在乎你想用来调用该方法的变量的编译时类型。

You need to change the declaration to use your specific class: 您需要更改声明以使用特定的类:

usercontrol1 usercontroltest = new usercontrol1();

Or you could use an implicitly typed local variable , which would have exactly the same effect: 或者,您可以使用隐式类型的局部变量 ,其效果完全相同

var usercontroltest = new usercontrol1();

That will fix the immediate problem, but: 这将解决当前的问题,但是:

  • Are you sure you really want to create a new instance here, rather than using one which is already on your form? 您确定要在这里创建一个实例,而不是使用表单上已经存在的实例吗?
  • You should get into the habit of following .NET naming conventions as soon as possible 您应该尽快养成遵循.NET命名约定的习惯
UserControl usercontroltest = new usercontrol1();

While this allocates a new usercontrol1 , it assigns it to its base class, UserControl . 虽然这分配了新的usercontrol1 ,但usercontrol1其分配给其基类UserControl UserControl has no test() method. UserControl没有test()方法。

You probably want: 您可能想要:

usercontrol1 usercontroltest = new usercontrol1();

instead. 代替。

还要确保对类名使用nerdcaps( http://c2.com/cgi/wiki?CapitalizationRules

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM