使用 new 和 override 在 DerivedClass 中将 BaseClass 属性更改为只读 [英] Change BaseClass property to readonly in DerivedClass with new and override
问题描述
我有一种情况,我想让普通属性在派生类中使用默认值只读.为此,我通过以下方式使用关键字 new:
I have a situation where I want to make normal property to be readonly in derived class with default value. I am using keyword new for that purpose in the following way:
public abstract class BaseClass
{
public virtual string SomeInfo { get; set; }
}
public class DerivedClass1 : BaseClass
{
public new string SomeInfo => "ChildInfo1"; // C# 6.0 equivalent of { get { return "ChildInfo1"; } }
}
它工作正常,并且 new DerivedClass1().SomeInfo
不能分配给 - 它是只读的.我知道可以通过基类访问它:
It works fine, and new DerivedClass1().SomeInfo
cannot be assigned to -- it is readonly. I'm aware that one could access it through base class:
BaseClass b1 = new DerivedClass1();
b1.SomeInfo = "ChildInfo1 changed";
我只是想让用户无法意外更改它,并且通过基类它会是故意的,在这种情况下它是可以接受的.
I just want to unable user to change it accidentally, and through base class it would be on purpose in which case it's acceptible.
但是,如果派生类是这样的:
However if Derived class would be like this:
public class DerivedClass2 : BaseClass
{
public override string SomeInfo => "ChildInfo2";
}
那么这个属性将是可访问的,您似乎可以更改它,但它不会被更改,我想了解为什么?
Then this property would be accessible and you could seemingly change it but it would not be changed, and I would like to understand why?
var d2 = new DerivedClass2();
d2.SomeInfo = "ChildInfo2 changed";
Console.WriteLine(d2.SomeInfo); // output: ChildInfo2
更新:
我添加了新答案作为第三个选项,可能是最好的.
UPDATE:
I have added new answer as third option, probably the best.
推荐答案
在你的基类中你有
public virtual string SomeInfo { get; set; }
这只是一个很好的定义:
It's just a nice definition of:
private string _someInfo;
public string SomeInfo
{
get {return _someInfo;}
set {_someInfo = value;}
}
如果您使用 Expression-Bodied 属性覆盖它,您将使用
if you override it with an Expression-Bodied property you override the get property with
public string SomeInfo
{
get {return "ChildInfo2";}
}
但是您没有覆盖 set 属性,因此您仍然可以设置私有变量,但它不会更改任何其他内容.
But you don't override set property, so you could still set the private variable, but it doesn' change anything else.
如果您查看第一个示例:
if you look on your first example:
BaseClass b1 = new DerivedClass1();
b1.SomeInfo = "ChildInfo1 changed";
发生完全相同的事情,您可以设置属性,因为基类确实有 setter 并设置了一个私有变量,但是如果您尝试输出 SomeProperty 的值,您会看到它没有更改并且仍然是ChildInfo1"
it happens exact the same thing, you could set property, because base class does have setter and sets a private variable, but if you try to output value of SomeProperty, you see, that it is not changed and is still "ChildInfo1"
这篇关于使用 new 和 override 在 DerivedClass 中将 BaseClass 属性更改为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!