Skip to main content
 首页 » 编程设计

c#之在 C# 中,如何从第一个类调用第二个类中的方法

2024年02月05日10mfryf

我想从 Program.cs 中的 main 调用 Alpha 类中的 Apple 方法和 Beta 类中的 Beet 方法。

我不明白我在下面的代码中做错了什么。

非常感谢您查看此问题!

我有一个只有三个非常简单的文件的新项目:

  • 程序.cs
  • Alpha.cs
  • Beta.cs

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(); 
        } 
    } 
} 

Alpha.cs

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();