【发布时间】:2017-09-08 07:24:02
【问题描述】:
我必须使用方法Apply 和Do 来转换或评估表达式。在下面的示例中,它们在泛型上下文中使用,泛型类型可以是值或引用。编译器允许某些用法,而另一些则被视为错误。失败示例和非失败示例的代码类似,只是失败示例是变量初始化。
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 => x);? -
@SeM:第二部分
c = a?.Apply(x => x);生成与示例中相同的错误。请参阅accepted answer 了解详情。
标签: c# generics compiler-errors