-1

目前,我们可以编写来检查这一点的代码只是列出所有可能的类型integral,如下所示:

public static bool IsIntegral(this Type type)
{
        return type == typeof(int) || type == typeof(uint) ||
               type == typeof(short) || type == typeof(ushort) ||
               type == typeof(long) || type == typeof(ulong) ||
               type == typeof(byte);
}

我想知道是否有一些更好更干净的方法不应该涉及任何与字符串转换/转换的技巧(我认为这不会很好,即使我们必须从 Type using 创建一些虚拟实例Activator)。

很遗憾,这样的事情不起作用:

typeof(long).IsAssignableFrom(type);

而实际上在代码中我们可以这样写:

int i = 5;
long l = i;//this looks much like long can be assignable from int

但实际上它们(long 和 int)在这里没有任何继承关系,编译器似乎在这里做了一些神奇的自动转换以使上述代码有效。

4

3 回答 3

1

这是从@Marc Gravell 的建议中提出的一个实现,关于 using Type.GetTypeCode,有趣的是代码范围从sbytetouint64是连续的512如此处所述https://docs.microsoft.com/en-us/dotnet/api/system. typecode?view=netframework-4.8)。所以假设它们没有改变(实际上它们不应该改变),我们可以有以下更整洁的代码:

public static bool IsIntegral(this Type type)
{
    var typeCode = (int) Type.GetTypeCode(type);
    return typeCode > 4 && typeCode < 13;
}

感谢您的反对,但我在这里学到了一些新东西:D

于 2019-06-10T16:06:49.260 回答
0

不确定这是否会更好,但如果需要,似乎更容易更改:

private static readonly Type[] integralTypes = new[] { typeof(int), typeof(uint), 
                                                       typeof(short), typeof(ushort),
                                                       typeof(long), typeof(ulong), 
                                                       typeof(byte) };

public static bool IsIntegral(this Type type)
{
    return integralTypes.Contains(type);
}
于 2019-06-10T15:56:25.480 回答
-4

你试试如何Int64.TryParse(value)成功的转换意味着它的一个整体价值。不过,您将不得不排除 bool 和 string。你也可以玩,IsNumber但你必须再次考虑字符串值。

鉴于此,我想最好的办法是编写一个辅助方法来根据可能的组合进行检查。

于 2019-06-10T15:49:30.607 回答