【发布时间】: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