给定 Msdn :常量表达式是可以在编译时完全评估的表达式。
但是在下面的示例代码中,我有一个无法在编译时评估的 contantExpression。
我应该错过了什么,但是什么?
public class SomeClass
{
public string Key { get; set; }
}
public static void Sample()
{
var wantedKey = Console.ReadLine();
Expression<Func<SomeClass, bool>> expression = c => c.Key == wantedKey;
var maybeAConstantExpression = ((MemberExpression)((BinaryExpression)expression.Body).Right).Expression;
//Both are true, so we have a constantExpression,righ and Value should be known
Console.WriteLine(maybeAConstantExpression.NodeType == ExpressionType.Constant);
Console.WriteLine(maybeAConstantExpression.GetType() == typeof(ConstantExpression));
var constantExpression = ((ConstantExpression)maybeAConstantExpression);
var constantValue = constantExpression.Value;
//ConsoleApplication1.Program+<>c__DisplayClass0
//Do not looks like a constant..this is a class...
Console.WriteLine(constantValue);
var fakeConstantValue = constantValue.GetType().GetField("wantedKey").GetValue(constantValue);
//Return the value entered whith Console.ReadLine
//This is not really known at compile time...
Console.WriteLine(fakeConstantValue);
}