类转换成字符串通过电子邮件发送 [英] Convert class to string to send via email

查看:144
本文介绍了类转换成字符串通过电子邮件发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建的领域需要获得通过电子邮件发送的形式。这是一个内部项目,所以时间安排很紧,邮件并不需要是pretty的。

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

我可以写了一些反思这样做没有太多的问题,但我很好奇,如果有一些已经内置在.NET可能为我做的。就像我说的,我在寻找的东西快速。

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.

推荐答案

您可以使用反射像这样的:

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();
}

这篇关于类转换成字符串通过电子邮件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆