简体   繁体   中英

C#: What's the String.Format form of this?

How can this easy to write (and read) string formatting routine be convert into the "proper" String.Format equivalent code?

Int32 power;
Single voltage;
Int32 kVA;
Double powerFactor;

powerFactor = power / kVA;

label1.Text = 
      DateTime.Now.ToString() + ": " + 
      power.ToString() + "W,  " + 
      voltage.ToString() + "V "+
      "(pf "+(powerFactor*100.0).ToString()+"%)";

//label1.Text = String.Format("{g}: {0:g}W, {0:g}V (p.f. {0:0%}%)", 
//      DateTime.Now, power, voltage, powerFactor);

I've spent about 10 minutes trying to use String.Format ; the person who documented it should be terminated.

string.Format("{0}: {1}W,  {2}V (pf {3}%",DateTime.Now,power,voltage,powerFactor*100)

So, here is the thing that I think is confusing you. Every {0} is the index of the objects you are passing in. {0} is the first object, {1} the second, and so forth. You can also specify formats, widths, and other things too numerous to list here. I use SteveX string ref for most of my needs.

label1.Text = String.Format("{0:g}: {1:g}W, {2:g}V (p.f. {3:0.0%})", 
      DateTime.Now, power, voltage, powerFactor);

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