我已经编写了以下代码来处理从数据库到数据类型的映射参数(相信我,我希望我可以使用标准ORM,但是由于许多原因,这是不可行的)
public void LoadDatabaseValue<T>(DataTable partData, string identifier, string mappingName, Expression<Func<T>> mappingProperty)
{
var partAttributeValue = mappingProperty.Name;
var memberExpression = (MemberExpression)mappingProperty.Body;
var prop = (PropertyInfo)memberExpression.Member;
try
{
var selectedRow = partData.Select($"partattributename = '{mappingName}'");
var selectedValue = selectedRow[0]["PartAttributeValue"];
var typedOutput = (T)Convert.ChangeType(selectedValue, typeof(T));
prop.SetValue(memberExpression.Expression, typedOutput, null);
}
catch (Exception exception)
{
_databaseImportError = true;
// code to log this error
}
当我尝试运行此程序时,出现以下异常
{System.Reflection.TargetException: Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index) }
当我调试它时,我的typedOutput会与我的属性类型对齐,因此我不确定为什么会引发此异常。
我用这样的方式称呼它
LoadDatabaseValue(partData, identifier, "Offset", () => Offset);
如果要保留当前的方法设计,则需要一种方法以某种方式评估memberExpression.Expression
以便能够调用SetValue
方法。
所以换行
prop.SetValue(memberExpression.Expression, typedOutput, null);
至
prop.SetValue(Evaluate(memberExpression.Expression), typedOutput, null);
然后使用以下实现之一:
(A)如果仅使用属性访问器,这将足够:
static object Evaluate(Expression e)
{
if (e == null) return null;
var me = e as MemberExpression;
if (me != null)
return ((PropertyInfo)me.Member).GetValue(Evaluate(me.Expression), null);
return ((ConstantExpression)e).Value;
}
(B)这是更通用的,但较慢:
static object Evaluate(Expression e)
{
if (e == null) return null;
return Expression.Lambda(e).Compile().DynamicInvoke();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句