【问题标题】:In C# how to call a method in a second class from the first class?在 C# 中,如何从第一类调用第二类中的方法?
【发布时间】:2015-12-16 22:02:59
【问题描述】:

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

我无法理解我在下面的代码中做错了什么。

非常感谢您查看此问题!

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

  • Program.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(); Beta b = new Beta(); a.Apple(); b.Beet();
  • Alpha a = new Alpha();和 Beta b = new Beta();
  • AlphaBeta 是类。 AppleBeet 是这些类中的成员函数。

标签: c# asp.net class methods


【解决方案1】:

你混合了类和方法。应该是:

Alpha a = new Alpha();
a.Apple();

【讨论】:

    【解决方案2】:

    您需要先创建对象,然后才能使用它们的方法。

    Alpha a = new Alpha();
    a.Apple();
    Beta b = new Beta();
    b.Beet();
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-21
        • 1970-01-01
        • 2015-08-20
        • 2022-01-21
        • 1970-01-01
        • 2016-12-11
        相关资源
        最近更新 更多