c# - 如何向下转换为重载方法

标签 c# relationship downcast

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

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 来调用此重载方法呢?是因为不知道选择哪种方法吗?我如何在代码中解释这一点并解决它?

最佳答案

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

编译器将无法理解您已经为每个子类型定义了一个子情况。一种解决方案是对其进行强制转换以检查您的对象是否实现子接口(interface)之一并调用强制转换对象上的方法。

当然,将其写在其余代码的中间并不是一个很好的解决方案。正如 SLAks 提到的,你应该使用调度,例如 here ,或使用 C# 4.0 关键字dynamic,如图 here

这是第二个链接的示例:

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); 
}

关于c# - 如何向下转换为重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19733010/

相关文章:

c# - 统一扩展

ruby-on-rails - 嵌套表单 - 如何将现有嵌套对象添加到父表单?

c# - IEnumerable - 移动到下一个

C# Windows Phone 8.1 语言选择

拉拉维尔。如何获得外键是数组的关系

python - 我如何在 python 中向下转换

c++ - 为什么涉及虚拟继承时不能使用static_cast进行向下转换?

c# - 在 C# 中将基实例转换为派生类(向下转换)

c# - XML 序列化 : The type of the argument object 'Sw' is not primitive

php - Laravel Eloquent ORM 复制