簡體   English   中英

C#:如何通過在主方法中調用 ToString 方法在控制台中打印出來

[英]C#: How to have a ToString method be printed out in the console by calling it in the main method

我正在嘗試讓“ToString() 方法”返回客戶的全名

喜歡

//Console.WriteLine("你的名字是" + fName + lName);

已經這樣做了,但是在 ToString 中。

class Program
{
    static void Main(string[] args)
    {
        var instance = new Customer();
    }
}

——

class Customer
{
    public string fName, lName;

    public Customer()
    {
        Console.WriteLine("Please enter your first name");
        fName = Console.ReadLine();
        Console.WriteLine("Please enter your last name");
        lName = Console.ReadLine();
        //Console.WriteLine("Your name is " + fName + lName);
    }

    public override string ToString()
    {
        return fName + lName;
        Console.WriteLine(fName + lName);
    }
}

任何關於如何解決這個問題的反饋都將不勝感激。 嘗試在 Main 中放入不同的東西,但始終無法編譯。

我同意設計不是最好的,對我來說也不是很清楚,但我會嘗試幫助你做幾個變化 1:

class Customer
{
    public string fName, lName;
    public Customer()
    {
        Console.WriteLine("Please enter your first name");
        fName = Console.ReadLine();
        Console.WriteLine("Please enter your last name");
        lName = Console.ReadLine();
        Console.WriteLine(ToString());
    }

    public override string ToString()
    {
        return fName + lName;
    }
}

2:

class Program
{
    static void Main(string[] args)
    {
        var instance = new Customer();
        Console.WriteLine(instance.ToString());
    }
}
//in Customer class
public override string ToString()
{
    return fName + lName;
}

3:在Customer類中編寫打印方法,並像“1:”一樣通過ctor調用它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM