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 有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我编写了一个程序,允许两个班级“战斗".无论出于何种原因,C# 总是获胜.VB.NET 有什么问题?


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01