今天遇到一些小问题,在使用正则表达式分析如下HTML代码
发现提取出来的内容全是配对的,并且是字符串。
有个实体类
现在问题来了,我们应该如何赋值呢?如果每次循环,那样效率太低了,不然怎么才能找通过中文找到对应的属性呢?
经过半个小时的研究,从EnumRemarkHelper中找到启发。可以通过发射+特性的方式找到对应的属性,并为其赋值。
public class FieldRemark : Attribute |
/// <param name="remark"></param> |
public FieldRemark( string remark) |
private static Dictionary<Type, Dictionary< string , FieldInfo>> dictionary = new Dictionary<Type, Dictionary< string , FieldInfo>>(); |
public static Dictionary<Type, Dictionary< string , FieldInfo>> FieldRemarkDictionary |
get { return FieldRemark.dictionary; } |
public static void GetFieldRemarks( object obj) |
Type type = obj.GetType(); |
FieldInfo[] v = type.GetFields(); |
Dictionary< string , FieldInfo> temp = new Dictionary< string , FieldInfo>(); |
foreach (FieldInfo v1 in v) |
object [] CustomAttributes = v1.GetCustomAttributes( typeof (FieldRemark), false ); |
if (CustomAttributes != null && CustomAttributes.Count() > 0) |
if (!temp.ContainsKey(((FieldRemark)CustomAttributes[0]).Remark)) |
temp.Add(((FieldRemark)CustomAttributes[0]).Remark, v1); |
dictionary.Add(obj.GetType(), temp); |
public class FieldRemarkHelper |
public static void SetValue( object obj, string attribute, object value) |
if (FieldRemark.FieldRemarkDictionary.Count <= 0) |
FieldRemark.GetFieldRemarks(obj); |
if (!FieldRemark.FieldRemarkDictionary.ContainsKey(obj.GetType())) |
FieldRemark.GetFieldRemarks(obj); |
if (FieldRemark.FieldRemarkDictionary.ContainsKey(obj.GetType())) |
Dictionary< string , FieldInfo> temp = FieldRemark.FieldRemarkDictionary[obj.GetType()]; |
if (temp.ContainsKey(attribute)) |
MethodInfo mi=temp[attribute].FieldType.GetMethod( "Parse" , new Type[] { value.GetType()}); |
temp[attribute].SetValue(obj, mi.Invoke(temp[attribute], new object [] { value })); |
temp[attribute].SetValue(obj, value ); |
throw new Exception( string .Format( "程序出现错误,{0}不存在备注为{1}的属性,无法赋值" , obj.GetType().Name, attribute)); |
throw new Exception( string .Format( "{0}类中并不存在带有备注的属性" , obj.GetType().Name)); |
使用起来就很方便了。
People peo = new People(); |
FieldRemarkHelper.SetValue(peo, "姓名" , "王五" ); |
FieldRemarkHelper.SetValue(peo, "性别" , 0); |
FieldRemarkHelper.SetValue(peo, "年龄" , 1); |
另:如果代码有问题,请大家指出,谢谢。
把自己的文章搬过来。嘿嘿。。。