Override .ToString method c#

后端 未结 7 2080
北海茫月
北海茫月 2020-11-27 07:52

Okay, so I wrote this program out of the exercise of a C# programming book (I\'m trying to learn here) and it asks for \"Override the ToString() method to return all

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 08:10

    You are returning a string that just says the phrase _name + _number + _date + _salary.

    What you likely wanted to do is build a string using those fields. If you wanted them all mushed together Concat would work, but it would be highly un-readable

    public override string ToString()
    {
        return String.Concat(_name, _number, _date, _salary);
    }
    

    However what would be better is to use Format and include labels with the values

    public override string ToString()
    {
        return String.Format("Name:{0}, Number:{1}, Date:{2}, Salary:{3}",_name, _number, _date, _salary);
    }
    

    If you are using C# 6 or newer you can use the following cleaner format

    public override string ToString()
    {
        return $"Name:{_name}, Number:{_number}, Date:{_date}, Salary:{_salary}";
    }
    

    Which is the exact same logic as the previous String.Format version.

提交回复
热议问题