前言
有固定格式用特定符號隔開的字串,要拆解後放進Class的方式如下
開始
要映射的Class
1
2
3
4
5
6
7
public class Shool
{
public string Teacher_Id { get; set; }
public string Teacher_Name { get; set; }
public string Student_ID { get; set; }
public string Student_Name { get; set; }
}
自動映射的靜態Method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static object stringToBject<T>(string sourceString)
{
string[] source = sourceString.Split(';');
var target = Activator.CreateInstance(typeof(T).GetTypeInfo());
var props = target.GetType().GetProperties();
for (int i = 0; i < source.Length; i++)
{
switch (props[i].PropertyType.FullName.Split('.')[1])
{
case "String":
target.GetType().GetProperty(props[i].Name).SetValue(target, source[i]);
break;
}
}
return target;
}
實際執行
1
2
3
4
5
static void Main(string[] args)
{
string format = "T_ID;T_NAME;S_ID;S_NAME";
Shool test = (Shool)stringToBject<Shool>(format);
}
靜態擴展
如下Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static class Extensions
{
public static T ToClass<T>(this string sourceString) where T : class
{
string[] source = sourceString.Split(';');
var target = Activator.CreateInstance(typeof(T).GetTypeInfo());
var props = target.GetType().GetProperties();
for (int i = 0; i < source.Length; i++)
{
switch (props[i].PropertyType.FullName.Split('.')[1])
{
case "String":
target.GetType().GetProperty(props[i].Name).SetValue(target, source[i]);
break;
}
}
T result = (T)target;
return result;
}
}
以下是使用方式
1
2
string format = "T_ID;T_NAME;S_ID;S_NAME";
Shool test = format.ToClass<Shool>();