简体   繁体   中英

Writing the string.format over multiple lines

public override string ToString()
{
    return String.Format("Name : {0} Date Of Birth : {1: dd/MM/yyyy} Gender : {2} Telephone : {3}", _name, _dob, _gender, _tel);
}

How would I change this so that each Heading is written on a separate line so name is on line 1, DOB line 2, Gender line 3, etc?

Multiline string literal. Prefix it with the "at" sign, @ , and you can put actual newlines in the string itself. Much more readable than \\r\\n .

public override string ToString() 
{ 
    return String.Format(
@"Name : {0}
Date Of Birth : {1: dd/MM/yyyy}
Gender : {2}
Telephone : {3}", 
    _name, _dob, _gender, _tel); 
}

I recommend that you use Environment.NewLine because you can trust it in different runtimes

return String.Format("Name : {1}{0}Date Of Birth : {2: dd/MM/yyyy}{0}Gender : {3}{0}Telephone : {4}",
    Environment.NewLine, _name, _dob, _gender, _tel);

I would go with this approach:

public override string ToString()
{
    var nl = Environment.NewLine;
    return
        $"Name : {_name}{nl}"
        + $"Date Of Birth : {_dob:dd/MM/yyyy}{nl}"
        + $"Gender : {_gender}{nl}"
        + $"Telephone : {_tel}";
}

Or this, if you think it is clearer:

public override string ToString()
{
    return
        $"Name : {_name}{Environment.NewLine}"
        + $"Date Of Birth : {_dob:dd/MM/yyyy}{Environment.NewLine}"
        + $"Gender : {_gender}{Environment.NewLine}"
        + $"Telephone : {_tel}";
}

Using the \\r and \\n carriage return and linefeed characters.

public override string ToString() 
{ 
    return String.Format("Name : {0}\r\nDate Of Birth : {1: dd/MM/yyyy}\r\nGender : {2}\r\nTelephone : {3}", _name, _dob, _gender, _tel); 
}

Ok, there is a new way in C# it is very readable and simple to implement; you should add a dollar sign($) before double qoute:

return $"Name : {_name}\r\nDate Of Birth : {_dob}\r\nGender : {_gender}\r\nTelephone : {_tel}"; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM