通过备注(Attribute)为实例赋值。
今天遇到一些小问题,在使用正则表达式分析如下HTML代码
<td>姓名</td><td>王五</td> <td>年龄</td><td>22</td> <td>性别</td><td>男</td>
发现提取出来的内容全是配对的,并且是字符串。
姓名 王五 年龄 22 性别 男
有个实体类
class people
{
string name;
int aeg;
int sex;
}
现在问题来了,我们应该如何赋值呢?如果每次循环,那样效率太低了,不然怎么才能找通过中文找到对应的属性呢?
经过半个小时的研究,从EnumRemarkHelper中找到启发。可以通过发射+特性的方式找到对应的属性,并为其赋值。
public class FieldRemark : Attribute
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="remark"></param>
public FieldRemark(string remark)
{
_remark = remark;
}
private string _remark;
/// <summary>
/// 备注
/// </summary>
public string Remark
{
get { return _remark; }
set { _remark = value; }
}
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);
}
}
}
if (temp.Count > 0)
{
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()});
if (mi != null)
{
temp[attribute].SetValue(obj, mi.Invoke(temp[attribute], new object[] { value }));
}
else
{
temp[attribute].SetValue(obj, value );
}
}
else
{
throw new Exception(string.Format("程序出现错误,{0}不存在备注为{1}的属性,无法赋值", obj.GetType().Name, attribute));
}
}
else
{
throw new Exception(string.Format("{0}类中并不存在带有备注的属性", obj.GetType().Name));
}
}
}
使用起来就很方便了。
public class People
{
[FieldRemark("姓名")]
public string name;
[FieldRemark("性别")]
public int sex;
[FieldRemark("性别")]
public int age;
}
People peo = new People();
FieldRemarkHelper.SetValue(peo, "姓名", "王五");
FieldRemarkHelper.SetValue(peo, "性别", 0);
FieldRemarkHelper.SetValue(peo, "年龄", 1);
另:如果代码有问题,请大家指出,谢谢。
浙公网安备 33010602011771号