使用了错误的方法派生类 [英] Derived class using the wrong method

查看:101
本文介绍了使用了错误的方法派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经简化了我的代码,这个

I have simplified my code to this

 internal class Program
{
    private static void Main(string[] args)
    {
        Child d = new Child();
        int i = 100;
        d.AddToTotal(i);

        Console.ReadKey();
    }

    private class Parent
    {
        public virtual void AddToTotal(int x)
        {
            Console.WriteLine("Parent.AddToTotal(int)");
        }
    }

    private class Child : Parent
    {
        public override void AddToTotal(int number)
        {
            Console.WriteLine("Child.AddToTotal(int)");
        }

        public void AddToTotal(double currency)
        {
            Console.WriteLine("Child.AddToTotal(double)");
        }
    }
}

的问题是,这个电话

public void AddToTotal(double currency)

虽然我用一个int调用它,它应该使用

although I am calling it with an int and it should be using

public override void AddToTotal(int number)

使用父返回预期的结果。

Using the parent returns the expected result.

 Parent d = new Child();
 int i = 100;
 d.AddToTotal(i);



更新:

Update:

由于@Jan和@azyberezovsky指着我的规范。我添加了一个虚拟的空方法对基类来解决这个问题现在。

Thanks to @Jan and @azyberezovsky for pointing me to the specification. I have added a virtual empty method to the base class to get around this for now.

推荐答案

一个的在一个类型T一个名称为N成员查找是如下处理:

首先,集合名为N的所有可访问成员在T和基类型的T声明构造。 的声明,其中包括一个替换修改为排除在集 的如果没有名为N存在的成员,都可以访问,那么查找产生不匹配,和下面的步骤不进行评估。

First, the set of all accessible members named N declared in T and the base types of T is constructed. Declarations that include an override modifier are excluded from the set. If no members named N exist and are accessible, then the lookup produces no match, and the following steps are not evaluated.

因此,当您使用儿童型

Child d = new Child();
int i = 100;
d.AddToTotal(i);



方法公共覆盖无效AddToTotal(INT数)被排除在集,我们只有一个方法,名称为N左边。 int是隐式转换为加倍,所以没有错误发生。

method public override void AddToTotal(int number) is excluded from set, and we have only one method with name N left. Int is converted implicitly to double, so no errors occured.

这篇关于使用了错误的方法派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆