【发布时间】:2014-09-17 19:12:46
【问题描述】:
考虑一下这个 Reactive Extensions sn-p(忽略它的实用性):
return Observable.Create<string>(async observable =>
{
while (true)
{
}
});
这不能与 Reactive Extensions 2.2.5 一起编译(使用 NuGet Rx-Main 包)。它失败了:
错误 1 以下方法或属性之间的调用不明确:'System.Reactive.Linq.Observable.Create
(System.Func ,System.Threading.Tasks.Task >)' 和 'System.Reactive.Linq.Observable.Create (System.Func ,System.Threading.Tasks.Task>)'
但是,在 while 循环中的任意位置添加 break 可以修复编译错误:
return Observable.Create<string>(async observable =>
{
while (true)
{
break;
}
});
完全可以在没有响应式扩展的情况下重现该问题(如果您想在不摆弄 Rx 的情况下尝试它会更容易):
class Program
{
static void Main(string[] args)
{
Observable.Create<string>(async blah =>
{
while (true)
{
Console.WriteLine("foo.");
break; //Remove this and the compiler will break
}
});
}
}
public class Observable
{
public static IObservable<TResult> Create<TResult>(Func<IObserver<TResult>, Task> subscribeAsync)
{
throw new Exception("Impl not important.");
}
public static IObservable<TResult> Create<TResult>(Func<IObserver<TResult>, Task<Action>> subscribeAsync)
{
throw new Exception("Impl not important.");
}
}
public interface IObserver<T>
{
}
忽略其中的 Reactive Extensions 部分,为什么添加 break 有助于 C# 编译器解决歧义?这如何用 C# 规范中的重载决议规则来描述?
我正在使用面向 4.5.1 的 Visual Studio 2013 Update 2。
【问题讨论】:
-
@Mic1780:什么时候编译器在检测到无限循环时会失败?以前从未见过……
-
@Mic1780 不知道你在说什么。 C# 编译器(实际上是大多数编译器)会愉快地编译一个无限循环,甚至像
while(true) {}这样简单
标签: c#