繁体   English   中英

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

[英]In C# how to call a method in a second class from the first class?

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

我无法理解以下代码中做错了什么。

非常感谢您解决这个问题!

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

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

字母

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

第一种选择-将AlphaBeta类声明为static (以及方法)。 比您可以在Main函数中调用方法

暂无
暂无

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

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