給定Msdn:常量表達式是一個可以在編譯時完全評估的表達式。ConstantExpression不是常量
但是在下面的示例代碼中,我有一個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);
}
要成爲一個常量表達式,您的'maybeAConstantExpression'應該保持一個常量值,但它不是,它依賴於運行時的控制檯讀取行;所以你的constantExpression不會在編譯時被評估。 – Jegan