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 有什么问题?
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01