Поведение интерфейса C# `IBinaryInteger.GetByteCount()`C#

Место общения программистов C#
Anonymous
Поведение интерфейса C# `IBinaryInteger.GetByteCount()`

Сообщение Anonymous »

Я обнаружил странное поведение при работе с числами в C# (.NET8 версии 8.0.400).
Я создал собственный тип для переноса чисел, это минимизированный код для демонстрации поведения:
struct Mystery(T value)
where T : IBinaryInteger
{
public T Value { get; } = value;

public int GetByteCount() => Value.GetByteCount();
}

Код выполнения:
Mystery mystery = new(short.MaxValue);

// Mystery mystery = new(new BigInteger(short.MaxValue)); // same behavior

Console.WriteLine(mystery.GetByteCount()); // 4
Console.WriteLine(mystery.Value.GetByteCount()); // 2
Console.WriteLine(((IBinaryInteger)mystery.Value).GetByteCount()); // 4

Выход:
4
2
4

Поскольку я создал тип Mystery для обертывания числа, я бы хотел, чтобы Mystery.GetByteCount() вела себя точно так же, как Value.GetByteCount()
code>.
Однако, как видно из результатов, мой код не работает должным образом.
Где я ошибся? Как мне изменить 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 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));
});
}


Подробнее здесь: https://stackoverflow.com/questions/790 ... tbytecount

Вернуться в «C#»