C# 调用基类型上使用的重写方法
在此代码中:C# 调用基类型上使用的重写方法,c#,inheritance,char,C#,Inheritance,Char,在此代码中: using System; namespace ConsoleApp1 { public class TextInput { protected string _text = ""; public void Add(char c) { _text += c; } public string GetValue() { r
using System;
namespace ConsoleApp1
{
public class TextInput
{
protected string _text = "";
public void Add(char c)
{
_text += c;
}
public string GetValue()
{
return _text;
}
}
public class NumericInput : TextInput
{
public new void Add(char c)
{
if (!char.IsDigit(c)) return;
_text += c;
}
}
public class Program
{
public static void Main(string[] args)
{
TextInput input = new NumericInput();
input.Add('1');
input.Add('a');
input.Add('0');
Console.WriteLine(input.GetValue());
Console.WriteLine(char.IsDigit('1'));
Console.WriteLine(char.IsDigit('a'));
Console.WriteLine(char.IsDigit('0'));
}
}
}
。。。调用Console.WriteLine(char.IsDigit('a')
正确返回False
,但在重写的Add
方法中,它总是返回True
显然,它调用
TextInput.Add()
而不是NumericInput.Add()
。是否可以在重写的Add()
方法中更正此问题?Main
中的代码可能不会更改 查看c#中的new和override之间的差异。另外,看看虚拟密钥
我现在不打算解释。在这里和网上有很多关于这方面的信息
MS文档:
更多信息请点击此处:
总而言之,在这种情况下使用override。两种方法都试一下,你就会明白它们是如何起作用的。
那里如果要实现方法重写,请在基类中使用
virtual
关键字,在派生类中使用override
关键字
namespace ConsoleApp1
{
public class TextInput
{
protected string _text = "";
//Virtual allows derived class to enhance its functionality.
public virtual void Add(char c)
{
_text += c;
}
....
}
public class NumericInput : TextInput
{
//Override function will add more functionality to base class function
public override void Add(char c)
{
if (!char.IsDigit(c)) return;
_text += c;
}
}
现在new
关键字不会覆盖基类函数,它将隐藏基类功能
如果要重写派生类中的函数,请使用override
而不是new
关键字
有关更多参考,请访问:为什么不使用抽象类: 由于我们有多个
add
实现,也不能在T
上使用运算符,所以将其声明为抽象并在派生类上实现
public abstract class Input<T>
{
protected T __input;
public abstract void Add(T c);
public T GetValue()
{
return __input;
}
}
public class NumericInput : Input<int>
{
public override void Add(int c)
{
__input += c;
}
}
public class TextInput : Input<string>
{
public override void Add(string c)
{
__input += c;
}
}
static void Main(string[] args)
{
var input = new NumericInput();
input.Add(1);
input.Add(2);
Console.WriteLine(input.GetValue());
var text = new TextInput();
text.Add("a");
text.Add("a");
text.Add("a");
Console.WriteLine(text.GetValue());
Console.ReadLine();
}
公共抽象类输入
{
受保护的T__输入;
公开摘要无效添加(TC);
公共T GetValue()
{
返回输入;
}
}
公共类数字输入:输入
{
公共覆盖无效添加(int c)
{
__输入+=c;
}
}
公共类TextInput:Input
{
公共覆盖无效添加(字符串c)
{
__输入+=c;
}
}
静态void Main(字符串[]参数)
{
变量输入=新的数值输入();
输入。添加(1);
输入。添加(2);
Console.WriteLine(input.GetValue());
var text=新文本输入();
正文。添加(“a”);
正文。添加(“a”);
正文。添加(“a”);
Console.WriteLine(text.GetValue());
Console.ReadLine();
}
MakeAdd
virtual并用override
keyword@AleksAndreev在这种情况下,这是唯一可能的选择吗?你能解释一下你为什么使用新关键字吗?如果您试图实现方法重写。第二件事,这里您正在创建基类TextInput
的实例并调用Add()
,执行将不会进入派生类中存在的方法将不会检查IsDigit()
条件。请给我们提供一些有效的例子这里是你的例子的输出:我认为这个答案会有很大帮助:它很好,但这不是java,所以不需要@override
。