C# “如果打算隐藏,则使用新关键字”警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19193821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Use the new keyword if hiding was intended" warning
提问by tony b
I have a warning at the bottom of my screen:
我的屏幕底部有一条警告:
Warning 1 'WindowsFormsApplication2.EventControlDataSet.Events' hides inherited member 'System.ComponentModel.MarshalByValueComponent.Events'. Use the new keyword if hiding was intended. C:\Users\myComputer\Desktop\Event Control\WindowsFormsApplication2\EventControlDataSet.Designer.cs 112 32 eventControl
警告 1“WindowsFormsApplication2.EventControlDataSet.Events”隐藏继承的成员“System.ComponentModel.MarshalByValueComponent.Events”。如果打算隐藏,请使用 new 关键字。C:\Users\myComputer\Desktop\Event Control\WindowsFormsApplication2\EventControlDataSet.Designer.cs 112 32 eventControl
If i double click on it, it comes up with:
如果我双击它,它会出现:
public EventsDataTable Events {
get {
return this.tableEvents;
}
Can anyone tell me how to get rid of this?
谁能告诉我如何摆脱这个?
采纳答案by wdavo
Your class has a base class, and this base class also has a property (which is not virtual or abstract) called Events which is being overridden by your class. If you intend to override it put the "new" keyword after the public modifier. E.G.
你的类有一个基类,这个基类也有一个名为 Events 的属性(它不是虚拟的或抽象的),它被你的类覆盖。如果您打算覆盖它,请将“new”关键字放在 public 修饰符之后。例如
public new EventsDataTable Events
{
..
}
If you don't wish to override it change your properties' name to something else.
如果您不想覆盖它,请将您的属性名称更改为其他名称。
回答by Aggressor
@wdavo is correct. The same is also true for functions.
@wdavo 是正确的。对于函数也是如此。
If you override a base function, like Update, then in your subclass you need:
如果你覆盖了一个基本函数,比如 Update,那么在你的子类中你需要:
new void Update()
{
//do stufff
}
Without the new at the start of the function decleration you will get the warning flag.
如果在函数声明开始时没有 new,您将获得警告标志。
回答by Joee
In the code below, Class A
implements the interface IShow
and implements its method ShowData
. Class B
inherits Class A
. In order to use ShowData
method in Class B
, we have to use keyword new
in the ShowData
method in order to hide the base class Class A
method and use override
keyword in order to extend the method.
在下面的代码中,Class A
实现了接口IShow
并实现了它的方法ShowData
。Class B
继承Class A
. 为了在 中使用ShowData
方法Class B
,我们必须new
在ShowData
方法中使用关键字来隐藏基类Class A
方法,使用override
关键字来扩展方法。
interface IShow
{
protected void ShowData();
}
class A : IShow
{
protected void ShowData()
{
Console.WriteLine("This is Class A");
}
}
class B : A
{
protected new void ShowData()
{
Console.WriteLine("This is Class B");
}
}
回答by James L.
The parent function needs the virtual
keyword, and the child function needs the override
keyword in front of the function definition.
父函数需要virtual
关键字,子函数需要override
函数定义前面的关键字。