重载函数的C# [英] overriding a function c#

查看:105
本文介绍了重载函数的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想掌握虚函数的使用控制台应用程序的概念。我只要我重写基类函数,返回baseclassname.functionname(参数)被自动插入我的函数体的注意。为什么会这样?



 类advanc 
{
公共虚拟INT计算(int类型的,整数b )
{
回报(A * b);
}
}

类ADVN:advanc
{
公共覆盖INT计算(INT A,INT B)
{
//自动插入
返回base.calc(A,b);
}
}


解决方案

通过覆盖一个虚函数您扩展基类的功能,然后调用基类的基本功能。



如果你删除了返回base.calc(A,b)'行,基类代码将不会执行。



如果你想完全取代的功能,这不是一个问题,但如果你要那么扩展功能,你也应该调用基类。



下面的代码演示了这种(只是把它在一个控制台应用程序)

 类advanc 
{
公共虚拟INT计算(INT A,INT b)
{
Console.WriteLine(称为基函数);
回报(A * B);
}
}

类ADVN:advanc
{
公共BOOL CallBase {搞定;组; }
公共覆盖INT计算(INT A,INT B)
{
Console.WriteLine(称为超控功能);

如果(CallBase)
{
返回base.calc(A,B);
}
,否则
{
收益A / B;
}
}
}

私有静态无效的主要()
{
ADVN一个=新ADVN();

a.CallBase = TRUE;
INT结果= a.calc(10,2);
Console.WriteLine(结果);

a.CallBase = FALSE;
结果= a.calc(10,2);
Console.WriteLine(结果);
Console.WriteLine(准备好了);
Console.ReadKey();
}


I was just trying to master the concept of virtual function using a console app. I noticed as soon as I override a base class function, return baseclassname.functionname(parameters) gets inserted in my function body automatically. Why does this happen?

class advanc
{
    public virtual int  calc (int a , int b)
    {        
         return (a * b);        
    }        
}

class advn : advanc
{
     public override int calc(int a, int b)
     {
          //automatically inserted
          return base.calc(a, b);
      }        
}

解决方案

By overriding a virtual function you expand the functionality of your base class and then call the base class for the 'base functionality'.

If you would remove the 'return base.calc(a,b)' line, the base class code would not execute.

If you want to completely replace the functionality this is not a problem but if you want to extend the functionality then you should also call the base class.

The following code demonstrates this (just put it in a Console Application)

class advanc
{
    public virtual int calc(int a, int b)
    {
        Console.WriteLine("Base function called");
        return (a * b);
    }
}

class advn : advanc
{
    public bool CallBase { get; set; }
    public override int calc(int a, int b)
    {
        Console.WriteLine("Override function called");

        if (CallBase)
        {
            return base.calc(a, b);
        }
        else
        {
            return a / b;
        }
    }
}

private static void Main()
{
    advn a = new advn();

    a.CallBase = true;
    int result = a.calc(10, 2);
    Console.WriteLine(result);

    a.CallBase = false;
    result = a.calc(10, 2);
    Console.WriteLine(result);
    Console.WriteLine("Ready");
    Console.ReadKey();
}

这篇关于重载函数的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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