考虑以下响应式扩展的代码片段(忽略其实用性):
return Observable.Create<string>(async observable =>
{
while (true)
{
}
});
使用NuGet Rx-Main包的Reactive Extensions 2.2.5无法编译。以下错误发生:
Error 1 The call is ambiguous between the following methods or properties: 'System.Reactive.Linq.Observable.Create<string>(System.Func<System.IObserver<string>,System.Threading.Tasks.Task<System.Action>>)' and 'System.Reactive.Linq.Observable.Create<string>(System.Func<System.IObserver<string>,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>
{
}
除去响应式扩展的部分,为什么添加break
可以帮助C#编译器解决歧义问题?如何用C#规范中的重载解析规则来描述这一点?
我使用的是针对4.5.1版本的Visual Studio 2013 Update 2。
while(true) {}
这样简单的循环。 - tnw