gpt4 book ai didi

c# - 在 C# 中检查盒装原始整数类型的数值的最快方法

转载 作者:行者123 更新时间:2023-11-30 12:59:39 26 4
gpt4 key购买 nike

<分区>

我需要编写一个具有以下语义的方法:

/// <summary>
/// Checks if <paramref name="x"/> is a boxed instance of a primitive integral type
/// whose numerical value equals to <paramref name="y"/>.
/// </summary>
/// <param name="x">An object reference. Can be <c>null</c>.</param>
/// <param name="y">A numerical value of type <see cref="ulong"/> to compare with.</param>
/// <returns>
/// <c>true</c> if <paramref name="x"/> refers to a boxed instance of type
/// <see cref="sbyte"/>, <see cref="short"/>, <see cref="int"/>, <see cref="long"/>,
/// <see cref="byte"/>, <see cref="ushort"/>, <see cref="uint"/>, or <see cref="ulong"/>,
/// whose numerical value equals to the numerical value of <paramref name="y"/>; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// This method checks only for numeric equality, even if its arguments are of different runtime types
/// (e.g. <c>2L</c> is considered to be equal to <c>2UL</c>).
/// </para>
/// <para>
/// This method returns <c>false</c> if <paramref name="x"/> is <c>null</c>
/// or refers to an instance of a reference type or a boxed instance of a value type except
/// the primitive integral types listed above (e.g. it returns <c>false</c> if <paramref name="x"/>
/// refers to a boxed instance of an <c>enum</c> type, <see cref="bool"/>, <see cref="char"/>, <see cref="IntPtr"/>,
/// <see cref="UIntPtr"/>, <see cref="float"/>, <see cref="double"/>, <see cref="decimal"/>, or <see cref="BigInteger"/>).
/// </para>
/// <para>
/// This method should not throw any exceptions, or cause any observable side-effects
/// (e.g. invoke a method that could modify the state of an object referenced by <paramref name="x"/>).
/// </para>
/// </remarks>
[Pure]
public static bool NumericalEquals(object x, ulong y)

实现应该尽可能快(假设输入数据没有预期的偏向参数x的某些类型或值),并且不应该使用unsafe 代码或 P/Invoke。当然,在最快的实现中,我更喜欢最简单和最短的实现。

我的解决方案如下:

public static bool NumericalEquals(object x, ulong y)
{
if (x is sbyte)
{
sbyte z = (sbyte)x;
return z >= 0 && y == (ulong)z;
}

if (x is short)
{
short z = (short)x;
return z >= 0 && y == (ulong)z;
}

if (x is int)
{
int z = (int)x;
return z >= 0 && y == (ulong)z;
}

if (x is long)
{
long z = (long)x;
return z >= 0 && y == (ulong)z;
}

if (x is byte)
{
return y == (byte)x;
}

if (x is ushort)
{
return y == (ushort)x;
}

if (x is uint)
{
return y == (uint)x;
}

if (x is ulong)
{
return y == (ulong)x;
}

return false;
}

您能提出更好的方法吗?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com