小编Pla*_*aje的帖子

“CS0109:成员‘member’不隐藏继承的成员。不需要 new 关键字” - 这实际上是真的吗?

我读过其他帖子和埃里克·利珀特(Eric Lippert)关于该主题的帖子,但还没有在任何地方看到这种确切的情况得到解决。 重写方法上的 C# 可选参数 可选 参数和继承

我正在尝试实现以下情况:

public class BaseClass
{//ignore rest of class for now
  public void DoThings(String str)
  {
    //dostuff
  }
}
public class DerivedClass: BaseClass
{//ignore rest of class for now
  new public void DoThings(String str, Int32 someint = 1)
  {
    //dostuff but including someint, calls base:DoThings in here
  }
}
Run Code Online (Sandbox Code Playgroud)

当我这样做时,编译器会在主题行中向我发出警告,表明我不需要使用 new 关键字,因为该方法不会隐藏继承的方法。但是,我没有看到从对象实例调用基本方法的方法,因此它对我来说看起来是隐藏的。

我希望它实际上被隐藏。如果不隐藏,其他用户有可能有一天直接调用基方法并破坏该类(这涉及线程安全)。

我的问题是,新方法实际上隐藏了继承的方法(编译器是错误的?)还是编译器正确,我需要做其他事情来隐藏原始方法?或者根本不可能达到预期的结果?

c# inheritance overriding compiler-warnings

1
推荐指数
1
解决办法
584
查看次数

标签 统计

c# ×1

compiler-warnings ×1

inheritance ×1

overriding ×1