2

我的代码中有一个小问题,我认为这很有趣:

foreach(ISceneNode node in (root as IGroupNode))
            {
                PreVisit(node);
                if (notFound == false)
                {
                    return node;
                }
                else
                    PostVisit(node);
            }

我试图在 ISceneNode 对象节点上调用 PreVisit 和 PostVisit 方法,这是其他类型节点的父类。但是,因为这是对象关系的“太笼统”,所以我不允许调用方法:

//methods
void PreVisit(IDrawableNode drawable)
    {
        string targetName = drawable.Name;
        Boolean notFound = true;
        CompareToTarget(targetName, notFound, drawable);
    }

    void PreVisit(ITransformNode transform)
    {
        string targetName = transform.Name;
        Boolean notFound = true;
        CompareToTarget(targetName, notFound, transform);
    }

    void PreVisit(IStateNode state)
    {
        string targetName = state.Name;
        Boolean notFound = true;
        CompareToTarget(targetName, notFound, state);
    }

    void PreVisit(IGroupNode group)
    {
        string targetName = group.Name;
        Boolean notFound = true;
        CompareToTarget(targetName, notFound, group);
    }

IGroupNode、IStateNode 等从 ISceneNode 派生出来……那为什么我不能只使用 ISceneNode 来调用这个重载方法呢?是因为它不知道选择哪种方法吗?如何在我的代码中解释这一点并解决它?

4

2 回答 2

2

当你调用你的方法时,对象是ISceneNode,因为你没有定义PreVisit(ISceneNode),它会找不到合适的方法。

编译器将无法理解您已经为每个子类型定义了一个子案例。一种解决方案是强制转换它以检查您的对象是否实现了其中一个子接口并在强制转换的对象上调用该方法。

当然,仅在其余代码中间编写它并不是一个很好的解决方案。正如 SLaks 所提到的,您应该使用调度,如这里,或使用 C# 4.0 关键字dynamic,如这里所示

这是第二个链接的示例:

class Animal 
{ 
}

class Cat : Animal 
{ 
}

class Dog : Animal 
{ 
}

以下是专业:

void ReactSpecialization(Animal me, Animal other) 
{ 
    Console.WriteLine("{0} is not interested in {1}.", me, other); 
}

void ReactSpecialization(Cat me, Dog other) 
{ 
    Console.WriteLine("Cat runs away from dog."); 
}

void ReactSpecialization(Dog me, Cat other) 
{ 
    Console.WriteLine("Dog chases cat."); 
}

现在这是在 C# 4.0 中定义双重调度的方式dynamic

void React(Animal me, Animal other) 
{ 
    ReactSpecialization(me as dynamic, other as dynamic); 
}

然后运行

void Test() 
{ 
    Animal cat = new Cat(); 
    Animal dog = new Dog(); 

    React(cat, dog); 
    React(dog, cat); 
}
于 2013-11-01T18:36:45.133 回答
1

C#dynamic很好地做到了这一点:

PreVisit((dynamic)node);

在运行时使用 C# 语义选择适当的方法。

于 2013-11-01T18:42:19.550 回答