我正在尝试创建一个具有多个类的程序。我在program.cs中插入了示例文本,但是每当我运行该程序时,它都不会输出该文本,而只会输出该程序的名称和类文件,例如Testprogram.Customer
我不能锻炼为什么。
银行代码为:
namespace CashMachine
{
class Bank
{
private string bankname;
private string location;
public Bank(string name, string location)
{
this.bankname = bankname;
this.location = location;
}
public string Getname()
{
return this.bankname;
}
public string Getlocation()
{
return this.location;
}
}
}
程序的cs代码为:
namespace CashMachine
{
class Program
{
static void Main(string[] args)
{
Bank b = new Bank("NatWest", "London");
{
Console.WriteLine(b);
}
Console.WriteLine();
Console.WriteLine();
Customer c = new Customer("Joe", "UK", "joelndn", "May");
Console.WriteLine(c);
Console.ReadKey();
}
}
}
答案 0 :(得分:2)
如果我们以Bank
的第一个示例为例,
Bank b = new Bank("NatWest", "London");
Console.WriteLine(b);
现在;系统不会自动知道您要写的关于Bank
的内容,但是object
的所有子类都有一个public virtual string ToString()
方法,用于创建类型的文本表示< / strong>,因此:这就是所谓的。 ToString()
的默认实现是输出类型名称,但是如果您想做更有趣的事情:告诉您想要的内容。
我建议:
public override string ToString()
{
return Getname();
}
您可以使用Customer
做类似的事情来告诉它默认的输出是什么。
或者:在输出代码中明确显示 ,即
Console.WriteLine(b.Getname());
最后,您可能想考虑使用属性代替例如Getname
之类的方法(使用现代C#语法):
class Bank
{
public string Name { get; }
public string Location { get; }
public Bank(string name, string location)
{
Name = name;
Location = location;
}
public override string ToString() => Name;
}