c#中如何利用反射设置属性值
来源:互联网 发布:手机淘宝页面怎么刷新 编辑:程序博客网 时间:2024/05/16 05:07
代码如下:
1 /// <summary>
2 /// 设置相应属性的值
3 /// </summary>
4 /// <param name="entity">实体</param>
5 /// <param name="fieldName">属性名</param>
6 /// <param name="fieldValue">属性值</param>
7 public static void SetValue(object entity, string fieldName, string fieldValue)
8 {
9 Type entityType = entity.GetType();
10
11 PropertyInfo propertyInfo = entityType.GetProperty(fieldName);
12
13 if (IsType(propertyInfo.PropertyType, "System.String"))
14 {
15 propertyInfo.SetValue(entity, fieldValue, null);
16
17 }
18
19 if (IsType(propertyInfo.PropertyType, "System.Boolean"))
20 {
21 propertyInfo.SetValue(entity, Boolean.Parse(fieldValue), null);
22
23 }
24
25 if (IsType(propertyInfo.PropertyType, "System.Int32"))
26 {
27 if (fieldValue != "")
28 propertyInfo.SetValue(entity, int.Parse(fieldValue), null);
29 else
30 propertyInfo.SetValue(entity, 0, null);
31
32 }
33
34 if (IsType(propertyInfo.PropertyType, "System.Decimal"))
35 {
36 if (fieldValue != "")
37 propertyInfo.SetValue(entity, Decimal.Parse(fieldValue), null);
38 else
39 propertyInfo.SetValue(entity, new Decimal(0), null);
40
41 }
42
43 if (IsType(propertyInfo.PropertyType, "System.Nullable`1[System.DateTime]"))
44 {
45 if (fieldValue != "")
46 {
47 try
48 {
49 propertyInfo.SetValue(
50 entity,
51 (DateTime?)DateTime.ParseExact(fieldValue, "yyyy-MM-dd HH:mm:ss", null), null);
52 }
53 catch
54 {
55 propertyInfo.SetValue(entity, (DateTime?)DateTime.ParseExact(fieldValue, "yyyy-MM-dd", null), null);
56 }
57 }
58 else
59 propertyInfo.SetValue(entity, null, null);
60
61 }
62
63 }
64 /// <summary>
65 /// 类型匹配
66 /// </summary>
67 /// <param name="type"></param>
68 /// <param name="typeName"></param>
69 /// <returns></returns>
70 public static bool IsType(Type type, string typeName)
71 {
72 if (type.ToString() == typeName)
73 return true;
74 if (type.ToString() == "System.Object")
75 return false;
76
77 return IsType(type.BaseType, typeName);
78 }
- c#中如何利用反射设置属性值
- c# 如何通过反射 获取\设置属性值
- c# 如何通过反射 获取\设置属性值、
- C#利用反射获取对象属性值
- C#利用反射获取属性的值
- C#利用反射获取对象属性值
- C# 通过反射获取/设置属性值
- C#利用反射遍历对象的属性和属性值
- c# 如何通过反射 获取属性值
- C#如何通过反射获取属性值
- 利用反射 获取android布局文件中设置的属性值
- C#反射设置属性值和获取属性值
- C#反射设置属性值和获取属性值
- Android 应用利用反射机制获取/设置系统属性值
- C#利用反射给实体属性赋值
- C#利用反射为属性赋值
- C# 获得对象属性和属性值 C#利用反射遍历对象的属性和属性值
- 如何利用C#自定义属性
- Log4j配置文件说明
- 推荐几个学些.NET的常用网站
- 内容分发网络(CDN)
- MMS协议解析
- 【经典之作】做网页经常用到的代码集合2
- c#中如何利用反射设置属性值
- PHP网页UTF8编码开发中空白的问题
- 关于QQ等级需要小时数引发的算法联想
- 查看、修改oracle字符集,查看oracle版本
- 【经典之作】做网页时经常用到的代码集合(3)
- Words to Live by 生活的忠告
- 关于方法CEikonEnv::Static()方法和宏iEikonEnv的使用区别
- 教你买虚拟主机不会受骗的九个方法
- 委托(一个主窗体统计多个从窗体的按钮单击的次数)