C# 根据实体类的属性动态生成字符串
情景:
目前有两个实体类:Student,ClassInfo.
public class Student {
public string Name { get; set; }
public string Sex { get; set; }
public string Age { get; set; }
}
public class Classinfo
{
public string Subject { get; set; }
public int Score { get; set; }
}
Student stu = new Student() { Name="张三",Sex="男",Age="18"}; Classinfo cla = new Classinfo() { Subject="语文",Score=89};
希望拼接生成一串动态的字符串(非使用string.Format)。里面的属性可以增加,删除,随意改变顺序。如:
--情况1 string msg = "学生:[Student.Name],[Student.Sex],[Student.Age]岁。课程得分:[Classinfo.Subject]:[Classinfo.Score]."; ---处理后结果输出 学生:张三,男,18岁。课程得分:语文:89. --情况2 string msg = "学生:[Student.Name],[Student.Age]岁。课程得分:[Classinfo.Subject]:[Classinfo.Score]."; ---处理后结果输出 学生:张三,18岁。课程得分:语文:89. --情况2 string msg = "[Student.Age]岁的[Student.Name]的[Classinfo.Subject]成绩:[Classinfo.Score]."; ---处理后结果输出 18岁的张三的语文成绩:89.
处理方法:
Student stu = new Student() { Name="张三",Sex="男",Age="18"}; Classinfo cla = new Classinfo() { Subject="语文",Score=89}; object[] sources = new object[] { stu,cla }; string msg = "学生:[Student.Name],[Student.Sex],[Student.Age]岁。课程得分:[Classinfo.Subject]:[Classinfo.Score]."; foreach (var source in sources) { if (source == null) continue; msg = MessageBodyFactory.GetMessageBody(source, msg); }
//msg中可以随意修改。。
string msg = "学生:[Student.Name],[Student.Sex]岁。课程得分:[Classinfo.Subject]:[Classinfo.Score].";
string msg = "[Student.Age]岁的[Student.Name]的[Classinfo.Subject]成绩:[Classinfo.Score].";
源码地址:https://files.cnblogs.com/gguozhenqian/ConsoleApplication1.zip