是在VB.NET进行不安全的运算有实用的方法呢? [英] Are there utility methods for performing unsafe arithmetic in VB.NET?

查看:234
本文介绍了是在VB.NET进行不安全的运算有实用的方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重写得到一个散列code。有一个点,

I'm overriding getting a hash code. There's a point where

Hash = 1210600964 * 31 + -837896230

这会导致一个发生OverflowException 。有没有一种方法,我可以使用,这样的:

which causes an OverflowException. Is there a method that I can use, something like:

Hash = addUnsafe(multiplyUnsafe(1210600964, 31), -837896230)

而无需我的项目链接到另一个程序集?我不想删除溢出检查。 dllimports 正常。

推荐答案

您可以做64位数字的数学,而不是再使用切断任何多余的

You can do the maths with 64-bit numbers instead and then use And to cut off any excess:

Option Infer On
' .....
Shared Function MultiplyWithTruncate(a As Integer, b As Integer) As Integer
    Dim x = CLng(a) * CLng(b)
    Return CInt(x And &HFFFFFFFF)
End Function

虽然,你可以在一个解决方案将C#和VB.NET项目,这可能是最简单的写一个类在C#中做了未经检查的算术,即使你并不热衷于增加提及另一个程序集。

Although, as you can mix C# and VB.NET projects in one solution, it might be easiest to write a class in C# to do the unchecked arithmetic, even if you are not keen on adding a reference to another assembly.

这甚至可能是写在C#中的功能也让您可以测试VB的函数返回的预期值是一个好主意。这就是我所做的检查上述code。

It might even be a good idea to write the functions in C# too so that you can test that the VB functions return the expected values. It's what I did to check the above code.

编辑:我被提示约瑟夫Nields'注释测试性能,它原来使用CLng函数,而不是Convert.ToInt64和和工作更快

I was prompted by Joseph Nields' comment to test for performance, and it turned out using CLng instead of Convert.ToInt64 and And works faster.

这篇关于是在VB.NET进行不安全的运算有实用的方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆