using System;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str = "Hello! This is {Student.Name}. My ID is {Student.ID}.";
//string str2 = "你好!我是{Student.Name},我的ID為{Student.ID}。";
int size = 0;
Student std = new Student();
std.Name = "Tim";
std.ID = "44123";
string[] temp = str.Split(' ');//以空白做分界來切割
//算出有幾個標籤
foreach (string a in temp)
{
//Console.Write(a + "\n");
if (a.IndexOf('{') != -1)
size++;
}
string[] token = new string[size];
int count = 0;
//把標籤拿出來並存入陣列
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].IndexOf('{') != -1)
{
token[count] = temp[i].Substring(0, temp[i].IndexOf('}') + 1);
count++;
}
}
//取物件的值
Type myType = typeof(Student);
PropertyInfo[] prop = myType.GetProperties();
count = 0;
//把標籤取代為值
foreach (var p in prop)
{
str = str.Replace(token[count], (string)p.GetValue(std));
count++;
}
Console.Write(str);
Console.Read();
}
}
class Student
{
public string Name { get; set; }
public string ID { get; set; }
}
留言
張貼留言