ie.*_*ie. 21 .net c# visual-studio-debugging
我正在调试以下代码:
class A
{
public virtual string X => "A";
}
class B : A
{
public bool OwnX { get; set; } = true;
public override string X
=> OwnX ? "B" : base.X; // (o)
}
class Program
{
static void Main() => Console.WriteLine(new B().X);
}
Run Code Online (Sandbox Code Playgroud)
我在标有的线上有一个断点(o).当断点命中时,我正在尝试评估base.X并获得其值"B":
问题是:为什么不"A"呢?
小智 -6
也许您应该阅读更多有关此内容的内容?:运算符 https://learn.microsoft.com/en-us/dotnet/articles/csharp/language-reference/operators/conditional-operator
由于默认值 OwnX 为 true。
尝试一下这段代码:
B b = new B();
b.OwnX = false;
Console.WriteLine(b.X);
Run Code Online (Sandbox Code Playgroud)
解释一下这段代码: public override string X => OwnX ?“B”:碱基.X;
使其更具可读性:
public override string X
{
get {
if (Ownx == true) // this is the default value.
{
return "B";
}
else{
return "A";
}
}
Run Code Online (Sandbox Code Playgroud)