使用另一个.cs文件类中的一个.cs文件类的方法 [英] Using a method from one .cs file class in another .cs files class
问题描述
我有2个.cs文件,每个都有一个类。如何在Form2.cs中的另一个类中的Form1.cs中调用一个方法?
I have 2 .cs files each with a class in it. How do I call a method in a class from Form1.cs in another class inside of Form2.cs?
看起来像这样...
Form1.cs
public partial class Class1 : ClassContainer
{
public void awesomeMethod()
{
}
}
Form2.cs
class Class2 : SomethingChanged
{
public void decentMethod()
{
}
}
awesomeMethod()里面的decentMethod()。
感谢。
I would like to call awesomeMethod() inside of the decentMethod(). Thanks.
推荐答案
为了调用类的实例方法,需要一个类的实例。因此,要调用Class1的awesomeMethod,必须创建一个Class1的实例:
In order to call an instance method of a class, you need an instance of a class. Thus, to call Class1's awesomeMethod, you must create an instance of Class1:
Class1 c = new Class1();
c.awesomeMethod();
从开始段落,听起来像两个实际类是两种不同的形式。在这种情况下,一个表单创建另一个表单的新实例并不意味着只是为了获取可能是助手方法的东西 - 创建第二个表单可能是一个很大的开销。你最好把帮助方法放在一个更轻松的单独类中。
From your opening paragraph, though, it sounds like the two actual classes are two different forms. In that case, it doesn't really make sense for one form to create a new instance of another form purely to get at what is presumably a helper method - creating that second form is potentially an awful lot of overhead. You'd be better off putting helper methods into a separate, more lightweight class.
这篇关于使用另一个.cs文件类中的一个.cs文件类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!