简体   繁体   中英

Inserting white space between class variables in a ToString method C#

I want to allow the user to be able to print a copy of a client if they desire. I was thinking off having the entire class object converted to string, then set into a rich text box control, in a format similar to the following:

Name: blah blah

Age: blah blah

Email: blah blah

Description: blah blah blah
blah blah blah blah blah

etc etc. Is there a simple way to accomplish the line spacing/special formatting?

Thanks in advance, Ari

Use format strings , for example:

string.Format("{0}: {1}{2}", "Name", this.Name, Environment.NewLine);

Use Environment.NewLine to get the correct newline character/s.

You can use String.Format() to provide your custom formatting:

class YourClass
{
    public override string ToString()
    {
        return String.Format(CultureInfo.CurrentCulture,
                             "Description: {0} {1}{2}{3}",
                             this.Name,
                             this.Age,
                             Environment.NewLine,
                             this.Email);
    }
}

This will output:

Description: Name 
Age Email

I assumed you have a class named Person you can override ToString method, to get all props value by reflection and print them out, So adding new property doesn't cause to any change in code:

        public override string ToString()
        {
            var props = GetType().GetProperties();

            string result = "";
            foreach (var prop in props)
            {
                var val = prop.GetValue(this, null);
                var strVal = val != null ? val.ToString() : string.Empty;
                result += prop.Name + " : " + strVal + Environment.NewLine;
            }
            return result;
        }

    }

Also you can Serialize it and just descerialize in Client side, It's easy by marking class as Serializable.

    public override string ToString()
    {
        return string.Join(Environment.NewLine, 
          GetType().GetProperties().Select( 
             item => item.Name + ": " + (item.GetValue(this, null) ?? string.Empty).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