我读到newmodifer隐藏了基类方法.
using System;
class A
{
public void Y()
{
Console.WriteLine("A.Y");
}
}
class B : A
{
public new void Y()
{
// This method HIDES A.Y.
// It is only called through the B type reference.
Console.WriteLine("B.Y");
}
}
class Program
{
static void Main()
{
A ref1 = new A(); // Different new
A ref2 = new B(); // Polymorpishm
B ref3 = new B();
ref1.Y();
ref2.Y(); //Produces A.Y line #xx
ref3.Y();
}
}
Run Code Online (Sandbox Code Playgroud)
为什么 …
为什么重新锐化要求我不要从抽象类中隐藏属性?它希望我使用'new',但这总是更可取吗?这似乎暗示隐藏变量使用户无法做base.property是一件坏事.
我对这个OO概念感到有些困惑,并且想知道是否有充分的理由支持或反对它.
我有
public abstract class baseClass{
protected string commonProperty {get; set;}
}
public abstract class moreSpecificBaseClass : baseClass {
// Resharper would prefer I use 'new' below
protected string commonProperty = "Some specific setting";
}
public class verySpecificClass : moreSpecificBaseClass {
// Some code
}
Run Code Online (Sandbox Code Playgroud)