【问题标题】:why does my method in class with not return any value? [duplicate]为什么我在课堂上的方法没有返回任何值? [复制]
【发布时间】:2020-08-24 01:55:39
【问题描述】:

我正在尝试实现一个接口并使用它的方法,但是当我创建一个 Star 对象并尝试使用方法时,它们不会打印任何内容。

公平的警告,我已经好几个月没有编码了,而且我对 C# 还是很陌生(大约一周),所以这太可怕了。

对于此代码中的任何问题的任何帮助将不胜感激

我的代码的第一部分:

    interface CelestialBody
    {
        string getName();
        string getType();
        List<string> getOrbitals();
        void addOrbitals(string Orbital);
    }
    enum CelestialBodyType { Star, Planet, Satellite }
    
    class Star : CelestialBody
    {
        private string _Name;
        private List<string> Planets;
        private readonly string Type = "Star";
        public string getType() { return Type; } // Planet, Sun, Satellite
       
        public string Name
        {
            set
            {
                _Name = value;
            }

            get
            {
                return _Name;
            }

        }
        public string getName() { return _Name; }
        public List<string> getOrbitals() { return Planets; }
        public void addOrbitals(string NewPlanet) { Planets.Add(NewPlanet); }



        public Star() : this("No Name") // Sets the default value of Name
        {
        }


        public Star(string Name) : this(Name, CelestialBodyType.Star) // Set the default value of Classification
        {
        }
        //Designated Constructor
        public Star(string Name, CelestialBodyType Star)
        {
            this.Name = Name;
        }

    }

    
}

我的代码的主要部分

 class Program
    {
        static void Main(string[] args)
        {
            Star star = new Star("The Sun");

            Console.Write(star.getName() + star.getType());
        }
    }
}

【问题讨论】:

  • 改用Console.WriteLine
  • 提示:使用属性(getter)而不是 Java 风格的 getFoo 方法。它使您的代码更简洁、更易于使用。
  • 为我工作...dotnetfiddle.net/z2mrek
  • 除了@Dai 提到的。 C# 中的方法一般以大写字母开头;例如: GetName() 而不是 getName() 。

标签: c# class interface getter setter


【解决方案1】:

我假设您使用的是 Visual Studio 2017 或 .NET Framework 而不是 .NET Core - 在这种情况下,问题是您的程序在写入控制台后立即退出,这将导致控制台输出窗口消失,因此为什么你看不到任何输出。

使用Console.ReadLine()将程序更改为在退出之前暂停:

static void Main(string[] args)
{
    Star star = new Star("The Sun");

    Console.WriteLine( star.getName() + star.getType() );

    Console.WriteLine( "Press [Enter] to exit." ); 
    Console.ReadLine();
}

VS2019 和 .NET Core 项目现在在您的进程退出后保持控制台输出窗口打开。

【讨论】:

    猜你喜欢
    • 2018-10-03
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多