假设我有一个抽象基类:
public abstract class BaseClass
{
private MyObject myObject;
protected MyObject PropA
{
get
{
if(myObject == null) this.myObject = new MyObject();
return this.myObject;
}
}
}
...并且在我的一个派生类中,我想使protected基类属性PropA
公开。使用 new
modifier 是否正确?在这种情况下?
public class DerivedClass : BaseClass
{
public new MyObject PropA
{
get
{
return base.PropA;
}
}
}
最佳答案
Would it be correct use of the new modifier in this context?
技术上 - 是的,不会有错误或警告。
对我来说,使用 new 关键字本身作为修饰符表明存在设计缺陷。
我举一个例子。
public class MyList<T> : List<T>
{
public int AddCallsCount;
public new void Add(T t)
{
AddCallsCount++;
base.Add(t);
}
}
[TestClass]
public class Test
{
[TestMethod]
public void TestThatsNotGood()
{
List<object> list = new MyList<object>();
list.Add(1);
list.Add(2);
MyList<object> myList = list as MyList<object>;
Assert.AreEqual(0, myList.AddCallsCount);
}
}
看起来多态有效,但实际上没有。
更新: 好的,有非常简单的解释。我省略了对多态性是什么的解释。
多态性是通过执行 abstract\virtual
实现的和 overriding
方法。一旦两者都没有 virtual
也不override
指定修饰符 MyList<T>.Add
只是另一种“常见”的公共(public)方法。和 MyList<T>
继承List<T>
, MyList<T>.Add
'隐藏' List<T>.Add
因为两个方法的名称和参数相同。
在较低级别:尽快List<T>
方法的类型定义 Add
未标有 virtual
关键字,编译器不会为给定类型的变量(在这种情况下为 MyList<T>
)搜索实际实例类型(在这种情况下为 List<T>
)的重写方法。
肯定会导致逻辑错误和类API的不正确使用。
因此,编译器“认为”可能存在逻辑错误或设计缺陷并警告程序员。 new
关键字只是与编译器对话的一种方式
yes, I know that it's not good, but I need it because of my bad design
.
关于c# - 正确使用 C# 'new' 修饰符使 protected 属性公开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693798/