I wrote a program that allow two classes to quot;fightquot;. For whatever reason C# always wins. What#39;s wrong with VB.NET?(我编写了一个程序,允许两个班级“战斗.无论出于何种原因,C# 总是获胜.VB.NET 有什么问题?)
问题描述
我写了一个程序,允许两个班级战斗".无论出于何种原因,C# 总是获胜.VB.NET 有什么问题?
I wrote a program that allow two classes to "fight". For whatever reason C# always wins. What's wrong with VB.NET ?
static void Main(string[] args)
{
Player a = new A();
Player b = new B();
if (a.Power > b.Power)
Console.WriteLine("C# won");
else if (a.Power < b.Power)
Console.WriteLine("VB won");
else
Console.WriteLine("Tie");
}
以下是选手:C# 中的玩家 A:
Here are the players: Player A in C#:
public class A : Player
{
private int desiredPower = 100;
public override int GetPower
{
get { return desiredPower; }
}
}
VB.NET 中的玩家 B:
Player B in VB.NET:
Public Class B
Inherits Player
Dim desiredPower As Integer = 100
Public Overrides ReadOnly Property GetPower() As Integer
Get
Return desiredPower
End Get
End Property
End Class
这是一个基类.
public abstract class Player
{
public int Power { get; private set; }
public abstract int GetPower { get; }
protected Player()
{
Power = GetPower;
}
}
推荐答案
这里的问题是 VB 在设置其字段值之前调用基本构造函数.所以基类 Player 存储零.
The issue here is that VB is calling the base constructor before setting its field value. So the base Player class stores zero.
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 15 (0xf)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [base]Player::.ctor()
IL_0006: ldarg.0
IL_0007: ldc.i4.s 100
IL_0009: stfld int32 B::desiredPower
IL_000e: ret
} // end of method B::.ctor
这篇关于我编写了一个程序,允许两个班级“战斗".无论出于何种原因,C# 总是获胜.VB.NET 有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!