如何自动赋值?
public void Hash2Object(Hashtable hash, object entityObject)
{
Type ty = entityObject.GetType();
BindingFlags.SetProperty, null, entityObject, values);
System.Reflection.PropertyInfo[] pis = ty.GetProperties();
string propertyName;
foreach (System.Reflection.PropertyInfo pi in pis)
{
propertyName = pi.Name;
object[] values = GetValueFromHashtable(hash, propertyName,pi.PropertyType);
if (values != null && values.Length > 0)
{
ty.InvokeMember(propertyName, BindingFlags.SetProperty, null, entityObject, values);
}
}
}
private static object[] GetValueFromHashtable(Hashtable hash, string key,Type type)
{
object value= hash[key] ;
return new object[] {value};
}
上面的代码是我根据网上的资料改的,意思是这样的:
首先Hashtable 的值是遍历页面控件获取的,为string类型,key为控件的ID,现在就是要遍历实体的属性,如果发现在hashtable中有指,则对该属性进行赋值.现在的问题就是,如果实体类的属性为string类型就不会有问题,可是如果是int类型或guid类型等其他类型就会出错.请各位帮忙,看看有什么办法可以解决这个问题.
谢谢