我遇到的 only valid safe 示例更具体地使用返回类型或在属性上提供 set 访问器.我并不是说只有这些,但我发现的只有这些。
例如,假设您有一个非常简单的基础,如下所示:
public abstract class Base
{
public string Name { get; protected set; }
public Base(string name)
{ Name = name; }
}
你可以有一个看起来更像这样的派生:
public class Derived : Base
{
public new string Name
{
get { return base.Name; }
set { base.Name = value; }
}
public Derived(string name) : base(name)
{ }
}
假设业务规则允许这个特定的 Derived 具有可更改的名称,我相信这是可以接受的。 new 的问题在于它会根据实例被视为什么类型来改变行为。例如,如果我说:
Derived d = new Derived("Foo");
d.Name = "Bar";
Base b = d;
b.Name = "Baz"; // <-- No set available.
在这个简单的例子中,我们很好。我们用new 覆盖了这个行为,但不是以破坏性的方式。更改返回类型需要更多技巧。也就是说,如果您使用new 更改派生类型的返回类型,则不应允许基类设置该类型。看看这个例子:
public class Base
{
public Base(Base child)
{ Child = child; }
public Base Child { get; private set; }
}
public class Derived
{
public Derived(Derived child) : base(child)
{ }
public new Derived Child
{ get { return (Derived)base.Child; } }
}
如果我可以在 Base 类中使用 set Child,我可能会在 Derived 类中遇到强制转换问题。另一个例子:
Derived d = new Derived(someDerivedInstance);
Base b = d;
var c = b.Child; // c is of type Base
var e = d.Child; // e is of type Derived
我不能通过将我所有的 Derived 类都视为 Base 来破坏任何业务规则,不进行类型检查和强制转换很方便。