通过反射实现DataRow对类进行赋值
2014-11-14 10:21:47 访问(1930) 赞(0) 踩(0)
/// <summary>
///
/// </summary>
public readonly static Type typeBoolean = typeof(Boolean);
/// <summary>
///
/// </summary>
public readonly static Type typeDateTime = typeof(DateTime);
/// <summary>
///
/// </summary>
public readonly static Type typelong = typeof(long);
/// <summary>
///
/// </summary>
public readonly static Type typeint = typeof(int);
/// <summary>
///
/// </summary>
public readonly static Type typestring = typeof(string);
/// <summary>
///
/// </summary>
public readonly static Type typeEnum = typeof(Enum);
/// <summary>
/// 转义枚举
/// </summary>
/// <param name="theValue"></param>
/// <returns></returns>
public static object ConvertEnumToValue(object theValue)
{
System.Enum em = (System.Enum)theValue;
IConvertible ic = (IConvertible)em;
if (ic == null)
new Exception("未知枚举值!");
try
{
return ic.ToInt64(null);
}
catch (Exception err)
{
throw err;
}
}
/// <summary>
///
/// </summary>
/// <param name="valueType"></param>
/// <param name="theValue"></param>
/// <returns></returns>
public static object GetObjectValue(Type valueType, object theValue)
{
if (theValue == null)
return null;
if (valueType == null)
return theValue;
if (valueType == typeEnum || valueType.BaseType == typeEnum)
return ConvertEnumToValue(theValue);
else
return theValue;
}
/// <summary>
/// 转义变量值
/// </summary>
/// <param name="valueType"></param>
/// <param name="theValue"></param>
/// <returns></returns>
public static object ConvertObject(Type valueType, object theValue)
{
if (theValue == null)
return null;
if (valueType == typestring)
{
if (theValue == null)
return null;
else
return theValue.ToString();
}
if (valueType == typeBoolean)
{
return GetBooleanNullByObj(theValue);
}
if (valueType == typelong)
{
return Convert.ToInt64(theValue);
}
if (valueType == typeint)
{
return Convert.ToInt32(theValue);
}
if (valueType.BaseType == typeEnum)
{
return Enum.Parse(valueType, theValue.ToString());
}
return theValue;
}
/// <summary>
///
/// </summary>
/// <param name="dr"></param>
public virtual void InitClassByDataRow(DataRow dr)
{
if (dr == null)
return;
DataTable dt = dr.Table;
Type thisType = this.GetType();
PropertyInfo pInfo = null;
foreach (DataColumn dc in dt.Columns)
{
pInfo = thisType.GetProperty(dc.ColumnName, BindingFlags.IgnoreCase);
if (pInfo == null)
continue;
pInfo.SetValue(this, ConvertObject(pInfo.PropertyType, dr[dc.ColumnName]), null);
}
}
标签:
通过反射实现DataRow对类进行赋值 


上一条:
下一条:
相关评论
发表评论