在 C# 中,要调用另一个类中的方法,需要:创建另一个类,包含要调用的方法;在使用该方法的类中实例化另一个类;使用实例化后的另一个类的变量来调用其方法。
如何用 C# 调用另一个类中的方法
在 C# 中,要调用另一个类中的方法,需要遵循以下步骤:
1. 创建另一个类
例如,创建一个名为 AnotherClass 的类,其中包含一个名为 AnotherMethod 的方法:
public class AnotherClass{ public void AnotherMethod() { // 方法实现 }}
登录后复制
2. 在使用该方法的类中实例化另一个类
例如,在名为 CallingClass 的类中实例化另一个类:
public class CallingClass{ public void CallAnotherMethod() { AnotherClass anotherClass = new AnotherClass(); }}
登录后复制
3. 调用方法
可以使用实例化后的另一个类的变量来调用其方法:
public void CallAnotherMethod() { AnotherClass anotherClass = new AnotherClass(); anotherClass.AnotherMethod(); }
登录后复制
示例代码:
以下是完整示例代码,演示了如何使用 C# 调用另一个类中的方法:
public class AnotherClass{ public void AnotherMethod() { Console.WriteLine("另一个类中的方法被调用了。"); }}public class CallingClass{ public void CallAnotherMethod() { AnotherClass anotherClass = new AnotherClass(); anotherClass.AnotherMethod(); } public static void Main(string[] args) { CallingClass callingClass = new CallingClass(); callingClass.CallAnotherMethod(); }}
登录后复制
以上就是c#怎么调用另一个类里面的方法的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3173517.html