[英]In C# how to call a method in a second class from the first class?
我想從Program.cs中的main調用Alpha類中的Apple方法和Beta類中的Beet方法。
我無法理解以下代碼中做錯了什么。
非常感謝您解決這個問題!
我有一個只有三個非常簡單的文件的新項目:
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// Note: there are red squiggly lines under Apple and Beet
// in Visual Studio.
Apple a = new Apple();
Beet b = new Beet();
}
}
}
字母
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class Alpha
{
public void Apple()
{
Console.WriteLine("From Alpha class A module");
}
}
}
Beta.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class Beta
{
public void Beet()
{
Console.WriteLine("From Beta class B module");
}
}
}
您混合了類和方法。 它應該是:
Alpha a = new Alpha();
a.Apple();
您需要先創建對象,然后才能使用它們的方法。
Alpha a = new Alpha();
a.Apple();
Beta b = new Beta();
b.Beet();
第一種選擇-將Alpha
和Beta
類聲明為static
(以及方法)。 比您可以在Main函數中調用方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.