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 有什么问题?


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01