Convert class to string to send via email

我们两清 提交于 2019-12-23 03:12:52

问题


I'm creating a form whose fields need to get sent via email. It's an internal project so timeline is tight and the email doesn't need to be pretty.

Is there a quick and dirty way to serialize/format a class into a readable string similar to this:

Field1Name:
This is the value of field1
Field2Name:
value of field 2

I could write up some reflection to do it without much issue, but I'm curious if there is something already built in to .NET that might do it for me. Like I said, I'm looking for something quick.


回答1:


You can use reflection like this:

public static string ClassToString(Object o)
{
    Type type = o.GetType();
    StringBuilder sb = new StringBuilder();
    foreach (FieldInfo field in type.GetFields())
    {
        sb.Append(field.Name).AppendLine(": ");
        sb.AppendLine(field.GetValue(o).ToString());
    }
    foreach (PropertyInfo property in type.GetProperties())
    {
        sb.Append(property.Name).AppendLine(": ");
        sb.AppendLine(property.GetValue(o, null).ToString());
    }
    return sb.ToString();
}



回答2:


If you don't want angle brackets or curly braces in the output, your best bet is to write a ToString() method for your class, and call it when you want to send the string representation. Should take you about five minutes.

public override string ToString()
{
    return "Field1Name: \n" + field1.ToString() +
           "\nField2Name: \n" + field2.ToString() +
           "\nField3Name: \n" + field3.ToString() + 
           "\nNestedObject: \n" + nestedObject.ToString();
}

Make sure you override ToString() for your nested object. :)



来源:https://stackoverflow.com/questions/15528330/convert-class-to-string-to-send-via-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!