【问题标题】:Get Value Type from ConstantExpression when Value is null当 Value 为 null 时从 ConstantExpression 获取值类型
【发布时间】:2016-01-13 14:37:14
【问题描述】:

当常量表达式值为空时,如何确定它的类型?我之前一直在使用下面的代码检测类型,但是当ConstantExpression值为null时会导致null异常。

static Type GetType(Expression expression)
{
    //causes exception when ((ConstantExpression)expression).Value is null
    if (expression is ConstantExpression)
        return ((ConstantExpression)expression).Value.GetType(); 

    //Check other types
}

想象一下我的表情是这样创建的:-

int? value = null;
ConstantExpression expression = Expression.Constant(value);

我想确定int类型?

【问题讨论】:

  • ((ConstantExpression)expression).Type?
  • 谢谢,这很简单!如果您添加答案,我可以接受。
  • 看起来问题比我想象的要棘手。当您获得 null 值的类型时,您将返回 System.Object(因为每种类型最终都派生自该类型)。因此,您无法确定实际的 type 是什么,例如int?。我在这里学习关于可空值和类型检查的新东西。这就是我如此喜欢 StackOverflow 的原因。
  • @JasonEvans 是的,但Expression.Constant() 有一个重载,它采用显式类型(只要它与值兼容),所以如果有人可能关心ConstantExpression' s 类型,创建时可以使用它。有关更多信息,请参阅我的答案。

标签: c# reflection


【解决方案1】:
expression.Type

但是,请注意,如果您使用问题中显示的工厂方法创建 ConstantExpression,结果将是 typeof(object),因为当工厂检查 value 时,它将获得一个空对象而不是可以打电话给GetType()。如果您要关心ConstantExpression 的类型,即使为null,您也需要使用传入类型参数的重载。这也意味着如果value 不是null,则返回的类型将是typeof(int),而不是typeof(int?)

Expression.Constant((int?)null).Type // == typeof(object)
Expression.Constant((int?)null, typeof(int?)).Type // == typeof(int?)
Expression.Constant(null, typeof(int?)).Type // == typeof(int?)
Expression.Constant((int?)3).Type // == typeof(int)
Expression.Constant((int?)3).Value.GetType() // == typeof(int)
Expression.Constant((int?)3, typeof(int?)).Type // == typeof(int?)
Expression.Constant(3, typeof(int?)).Type // == typeof(int?)

最后,但同样重要的是:

Expression.Constant(null, typeof(int)) // ArgumentException thrown, "Argument types do not match"

【讨论】:

  • 感谢详细的解释,很有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多