C#类未打印出来

时间:2019-03-13 16:40:29

标签: c#

我正在尝试创建一个具有多个类的程序。我在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();
        }
    }
}

1 个答案:

答案 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;
}