C# - 不能在 lambda 表达式中使用“is”运算符

gee*_*eko 4 c# lambda expression operators

我正在使用带有以下代码的 AgileMapper:

source.Map().OnTo(target, (options) =>
  options.IgnoreSources((options) =>
    options.If((value) =>  value is null)
  )
);
Run Code Online (Sandbox Code Playgroud)

但是,编译器抱怨:

表达式树可能不包含模式匹配的“is”表达式

如果我使用它会起作用value == null,但我想了解为什么is不起作用?

Jon*_*eet 19

value is null使用常量模式。模式匹配是在 C# 7 中引入的,在表达式树之后很久,并且不能(当前)在表达式树中使用。这可能会在某个时候实施,但目前它是无效的。请注意,这仅适用于表达式树 - 而不是转换为委托的 lambda 表达式。例如:

using System;
using System.Linq.Expressions;

class Program
{
    static void Main()
    {
        object x = null;
        Func<bool> func = () => x is null; // Fine
        Expression<Func<bool>> expression = () => x is null; // CS8122
    }
}
Run Code Online (Sandbox Code Playgroud)

表达式树中的代码有各种限制。例如,您不能使用动态操作或元组文字。对模式匹配的限制只是另一个例子。