我在 C#(.NET8 版本)中处理数字时发现了一些奇怪的行为8.0.400
。
我创建了一个自定义类型来包装数字,这是展示行为的最小化代码:
struct Mystery<T>(T value)
where T : IBinaryInteger<T>
{
public T Value { get; } = value;
public int GetByteCount() => Value.GetByteCount();
}
执行代码:
Mystery<BigInteger> mystery = new(short.MaxValue);
// Mystery<BigInteger> mystery = new(new BigInteger(short.MaxValue)); // same behavior
Console.WriteLine(mystery.GetByteCount()); // 4
Console.WriteLine(mystery.Value.GetByteCount()); // 2
Console.WriteLine(((IBinaryInteger<BigInteger>)mystery.Value).GetByteCount()); // 4
输出:
4
2
4
由于我创建了Mystery
用于环绕数字的类型,因此我希望mystery.GetByteCount()
其行为与 完全相同Value.GetByteCount()
。但是,如输出所示,我的代码并未按预期工作。
我哪里做错了?我应该如何修改我的Mystery.GetByteCount()
才能使其返回预期结果Value.GetByteCount()
?
以下是 NUnit 测试,用于阐明预期行为:
[TestCase(0)] // expect 1, but was 4
[TestCase(byte.MaxValue)] // expect 2, but was 4
[TestCase(short.MaxValue)] // expect 2, but was 4
[TestCase(char.MaxValue)] // expect 3, but was 4
[TestCase(int.MaxValue)] // expect 4, PASSED
[TestCase(long.MaxValue)] // expect 8, PASSED
public void MysteryBigInt_GetByteCount(long value)
{
Mystery<BigInteger> mystery = new(value);
BigInteger bigInt = new(value);
int expectedByteCount = bigInt.GetByteCount();
Assert.Multiple(
() =>
{
// PASSED
Assert.That(mystery.Value.GetByteCount(), Is.EqualTo(expectedByteCount));
// ony passed for int and long
Assert.That(mystery.GetByteCount(), Is.EqualTo(expectedByteCount));
});
}