简体   繁体   中英

using "{0} of {1}" in a ToString

Printing out a deck of cards I have a tostring in my class that reads

public override string ToString(){
  return GetCard() + " of " + GetSuit();}//end ToString

but I want all of the results to be in even columns so I tried

public override string ToString(){
  return "{0,5}of{1}",GetCard(),GetSuit();}//end ToString

and I don't think I can do that and I get an error. Is there another way to modify a tostring so I make even columns?

You, probably, are looking for string interpolation :

 public override string ToString() => $"{GetCard(),5} of {GetSuit}";

please, note the syntax : $ before the interpolated atring and values in braces "...{value}..."

solved using

public override string ToString(){
return $"{GetCard(),-2} of {GetSuit()}";}//end ToString```

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