5

为什么不能声明 type 的类常量字段Lambda Expression。我想要这样的东西:

class MyClass
{
   public const Expression<Func<string,bool>> MyExpr = (string s) => s=="Hello!";
}

但我得到编译错误:Expression cannot contain anonymous methods or lambda expressions

4

2 回答 2

8

This is just a limitation of C# and CLR. Only primitive numeric values, string literals and null can be used as a value of a constant field. Expression trees are represented as a normal graph of objects and can't appear as a constant value.

于 2013-10-05T14:30:43.740 回答
4

Reproduced. That is a strange error message from the compiler. I would expect instead:

error CS0134: '(field)' is of type '(type)'. A const field of a reference type other than string can only be initialized with null.

The message we do get is misleading. Some C# expressions (I am not talking about .NET expression trees Expression<...>) can clearly contain a lambda expression, but they don't say why this particular expression cannot.

The solution is to make a static readonly field instead:

class MyClass
{
   public static readonly Expression<Func<string, bool>> MyExpr
     = s => s == "Hello!";
}

Only one instance of Expression<> will ever be created, but it is no compile-time constant, there is actually some code that will run once (just) before MyClass is used for the first time.

于 2013-10-05T14:33:03.753 回答