1,将反射值转成int index值
PropertyInfo[] propertys = Model.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{ if (!pi.CanRead) continue;
object ValuesO = pi.GetValue(Model, null);
object SetValue =null;
if (ValuesO != null)
{
if (pi.PropertyType.FullName=="System.Boolean")//如果是布尔结构直接这样转换成数据库的1-0
{
SetValue = (bool)ValuesO ? 1 : 0;
}
else if (pi.PropertyType.IsEnum)
{
object valueGet = pi.GetValue(Model, null); //获取传入的对象属性下的当前枚举值
var fields = pi.PropertyType.GetFields(BindingFlags.Static | BindingFlags.Public);//获取所有枚举值下的数据
object aaa = "";
for (int i = 0; i < fields.Length; i++)
{
var ValueInEn = fields[i].GetValue(null).ToString();
if (ValueInEn == valueGet.ToString())
{
SetValue = i;//将枚举值转换为index值
break;
}
}
}
else
{
SetValue = ValuesO;
}
DICValue.Add(pi.Name, SetValue.ToString());
}
else
{
continue;
}
}
2,将index值转换为枚举值
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
{
if (value.GetType().FullName == "System.Int64")
{
value = Int32.Parse(value.ToString());
}
else if (pi.PropertyType.FullName == "System.Int32")
{
value = Int32.Parse(value.ToString());
}
else if (pi.PropertyType.FullName == "System.DateTime")
{
value = DateTime.Parse(value.ToString());
}
else if (pi.PropertyType.FullName == "System.Double")
{
value = double.Parse(value.ToString());
}
else if (pi.PropertyType.FullName == "System.Boolean")
{
string ValueThis = value.ToString().ToLower();
value = ValueThis == "true" ? true : false;
}
else if (pi.PropertyType.FullName == "System.Decimal")
{
value = decimal.Parse(value.ToString());
}
else if (pi.PropertyType.IsEnum)
{
int Index = Int32.Parse(value.ToString());//将数据库存的枚举值转换为int 作为index标记
var fields = pi.PropertyType.GetFields(BindingFlags.Static | BindingFlags.Public);//所有的数据值
if (Index>fields.Length-1)//如果超出限制,显示为0
{
Index = 0;
}
for (int i = 0; i < fields.Length; i++)
{
var valuethi = fields[i].GetValue(null);
if (Index == i)
{
value = valuethi;//找到对应的值 赋值给正常属性
}
}
}
pi.SetValue(t, value, null);
}
}
}
ts.Add(t);
}
关于枚举的介绍:
enum MyEnum
{
AAA, BBB, CCC
}
以此为例介绍下
背后的IL是这样的:
.class private auto ansi sealed MyEnum extends [mscorlib]System.Enum
{
.field public static literal valuetype Mgen.MyEnum AAA = int32(0)
.field public static literal valuetype Mgen.MyEnum BBB = int32(1)
.field public static literal valuetype Mgen.MyEnum CCC = int32(2)
.field public specialname rtspecialname int32 value__
}
实际返回的 fields下面的任何一个对象都是Enum可以直接赋值给数据反射的对象,如果是 tostring 数据就可以进行比对。
var fields = typeof(MyEnum).GetFields(BindingFlags.Static | BindingFlags.Public);//可以替换成pi.PropertyType.GetFields(BindingFlags.Static | BindingFlags.Public);
foreach (var fi in fields)
Console.WriteLine(fi.Name);
参考资料:https://www.cnblogs.com/xingbo/p/4031474.html