在程序中,我使用dynamic关键字来调用最佳匹配方法.但是,我发现框架StackOverflowException在某些情况下会崩溃.
我试图尽可能地简化我的代码,同时仍能够重新产生这个问题.
class Program
{
static void Main(string[] args)
{
var obj = new SetTree<int>();
var dyn = (dynamic)obj;
Program.Print(dyn); // throws StackOverflowException!!
// Note: this works just fine for 'everything else' but my SetTree<T>
}
static void Print(object obj)
{
Console.WriteLine("object");
}
static void Print<TKey>(ISortedSet<TKey> obj)
{
Console.WriteLine("set");
}
}
Run Code Online (Sandbox Code Playgroud)
如果新建的实例实现了接口并打印了"对象",则该程序通常会打印"set" ISortedSet<TKey>.但是,通过以下声明,将StackOverflowException抛出a (如上面的注释中所述).
interface ISortedSet<TKey> { }
sealed class SetTree<TKey> : BalancedTree<SetTreeNode<TKey>>, ISortedSet<TKey> {}
abstract class BalancedTree<TNode>
where TNode : …Run Code Online (Sandbox Code Playgroud)