【问题标题】:Operator '?' cannot be applied during initialization操作员 '?'初始化期间无法应用
【发布时间】:2017-09-08 07:24:02
【问题描述】:

我必须使用方法ApplyDo 来转换或评估表达式。在下面的示例中,它们在泛型上下文中使用,泛型类型可以是值或引用。编译器允许某些用法,而另一些则被视为错误。失败示例和非失败示例的代码类似,只是失败示例是变量初始化。

    public static U Apply<T, U>(this T subject, Func<T, U> f) => f(subject);

    public static void Do<T>(this T subject, Action<T> action) => action(subject);

    public static void SomeMethodA<A>(A a = default(A))
    {
        // OK: apply some operation to 'a'.
        a?.Apply(_ => default(A));

        // OK: apply some operation to 'a' and 'Do' assign result to 'b'.
        A b = default(A);
        a?.Apply(x => x).Do(x => b = x);
        a?.Apply(x => x)?.Do(x => b = x);

        // Bad: apply some operation to 'a' and initialize 'c' and 'd' with result.
        A c = a?.Apply(x => x);  // Error CS0023  Operator '?' cannot be applied to operand of type 'A'
        var d = a?.Apply(x => x);  // Error CS0023  Operator '?' cannot be applied to operand of type 'A'
    }

为什么初始化代码不编译,非初始化代码编译,错误代码(CS0023)与什么有关?

【问题讨论】:

  • 这样写有什么问题:A c = default(A); c = a?.Apply(x =&gt; x);?
  • @SeM:第二部分c = a?.Apply(x =&gt; x); 生成与示例中相同的错误。请参阅accepted answer 了解详情。

标签: c# generics compiler-errors


【解决方案1】:

您的问题几乎与Operator '?' cannot be applied to operand of type 'T' 重复。

基本问题是A 不可为空。或者至少,不知道可以为空。为了使您的分配工作,编译器必须能够在短路情况下生成null,并将其分配给局部变量。它不能。因此出现错误。

那么,为什么a?. 的其他用法没有错误?因为这些表达式永远不会分配给任何东西。如果没有赋值,短路就可以了,因为编译器不必假设可能不正确的事情,也不必做不可能的事情。

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2022-11-20
    • 1970-01-01
    • 2011-07-14
    相关资源
    最近更新 更多