反射(1)
反射例子
private static Dictionary<int, string> templates;
static void Main(string[] args)
{
templates = new Dictionary<int, string>();
templates.Add(1, "我是{Name},我住在{Address}。");
var testModelOne = new { Name = "张三", Address = "北京" };
var testModelTwo = new { Name = "李四", Address = "上海" };
Common(testModelOne, 1);
Common(testModelTwo, 1);
Console.ReadLine();
}
public static void Common<T>(T model, int id)
{
var template = templates[id];
var properties = model.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
object obj = propertyInfo.GetValue(model, null);
if (obj != null)
{
template = template.Replace("{" + propertyInfo.Name + "}", obj.ToString());
}
}
Console.WriteLine(template);
}
结果:
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。