1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace FLY.OBJComponents.Common
{
public static class PropertiesManager_JSON
{
/// <summary>
/// 设定参数(属性)的值,触发属性值变化“通知”,writeVal
/// </summary>
/// <param name="propertyName">属性名</param>
/// <param name="val">属性值</param>
public static void SetValue(object obj, string propertyName, object v)
{
PropertyInfo property;
try
{
property = obj.GetType().GetProperty(propertyName);
}
catch(Exception e)
{
throw new Exception("PropertiesManager_JSON 类型="+obj.GetType().ToString()+" 不能找到 属性名=" + propertyName, e);
}
if (property == null) {
throw new Exception("PropertiesManager_JSON 类型=" + obj.GetType().ToString() + " 不能找到 属性名=" + propertyName);
}
if (!property.CanWrite) {
throw new Exception("PropertiesManager_JSON 类型=" + obj.GetType().ToString() + " 属性名=" + propertyName +" 不能set");
}
if (property != null)
{
if (v == null)
{
property.SetValue(obj, v, null);
}
else if (v.GetType() == property.PropertyType)
{
property.SetValue(obj, v, null);
}
else
{
string json = JsonConvert.SerializeObject(v);
v = JsonConvert.DeserializeObject(json, property.PropertyType);
property.SetValue(obj, v, null);
}
}
}
}
}