gpt4 book ai didi

c# - 使用可为 null 的 DateTime 转换表达式会出错

转载 作者:行者123 更新时间:2023-11-30 21:53:40 30 4
gpt4 key购买 nike

在一个类中,我有一个通过提供表达式来获取 PropertyInfo 的静态方法。

public static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> expressie)
{
MemberExpression me;
switch (expressie.Body.NodeType)
{
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
var ue = expressie.Body as UnaryExpression;
me = ((ue != null) ? ue.Operand : null) as MemberExpression;
break;
default:
me = expressie.Body as MemberExpression;
break;
}
if (me == null)
{
throw new InvalidOperationException("Expression does not refer to a property: " + expressie.ToString());
}

return (PropertyInfo)me.Member;
}

为了使我的代码更加类型安全,我更改了我在调用此函数的部分方法中使用的表达式。

// Old
Expression<Func<T, Object>> expression;

// New (TProp instead of Object)
Expression<Func<T, TProp>> expression;

因此,我不能再使用旧的“GetPropertyInfo”方法,因为表达式与请求的参数不匹配。所以我创建了一个新的。

public static PropertyInfo GetPropertyInfo<T, TProp>(Expression<Func<T, TProp>> expressie)
{
MemberExpression me;
switch (expressie.Body.NodeType)
{
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
var ue = expressie.Body as UnaryExpression;
me = ((ue != null) ? ue.Operand : null) as MemberExpression;
break;
default:
me = expressie.Body as MemberExpression;
break;
}
if (me == null)
{
throw new InvalidOperationException("Expression does not refer to a property: " + expressie.ToString());
}

return (PropertyInfo)me.Member;
}

这个新表达式的主体与现有表达式的主体完全相同。因为我想坚持 DRY 原则,所以我寻找了一种在两种情况下都使用一个方法体的方法。这可以通过首先将“Expression >”转换为“Expression >”并将转换后的表达式传递给“旧”GetPropertyInfo(...) 方法来实现。我无法完全删除旧的“GetPropertyInfo”方法,因为其他代码片段仍然依赖它。

我使用的转换方法如下:

private static Expression<Func<T, object>> convertToObjectExpression<T, TProp>(Expression<Func<T, TProp>> expression)
{
return Expression.Lambda<Func<T,object>>(
Expression.Convert(expression.Body, typeof(object)),
expression.Parameters);
}

这工作正常,除非我使用的表达式具有可为空的 DateTime(DateTime?)作为 TProp 的类型。在这种情况下,以下行导致“我”为空。

me = ((ue != null) ? ue.Operand : null) as MemberExpression;

有人知道是什么导致了这个问题吗?

我有一个 fiddle包含问题。

最佳答案

我建议你反其道而行之。不要从你的新类型安全方法传递到旧方法(有所有附加问题),而是从旧方法传递到新方法:

// relay old interface to new one for compatibility
public static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> expressie)
{
return GetPropertyInfo<T, object>(expressie);
}

public static PropertyInfo GetPropertyInfo<T, TProp>(Expression<Func<T, TProp>> expressie)
{ /* your code, as you provided it */ }

如果您仍然遇到问题,请提供您的调用代码

编辑

因与问题无关而被删除

关于c# - 使用可为 null 的 DateTime 转换表达式会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33735041/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com