OverflowException only in VB.net, not in C#

后端 未结 2 1687
南旧
南旧 2021-01-19 04:05

for self educational purposes I tried to find a way to create a height map all by myself. I googled a little bit and found a function that creates pseudo-random numbers.

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-19 04:31

    Like D Stanley pointed out, the reason for the OverFlowException in VB.net is that VB.net is automatically doing an overflow check on integer operations while C# is not.

    In case someone else is interested in getting it to work in VB.net you can do the following:

    Add this structure to your project

    
    Public Structure LongToIntegerNoOverflow
        
        Public LongValue As Long
        
        Public IntValue As Integer
    End Structure
    

    and change the Noise function to

    Private Function Noise(ByVal x As Integer) As Single
        Dim x1 As Long
        Dim x2 As LongToIntegerNoOverflow
        Dim x3 As LongToIntegerNoOverflow
        Dim x4 As Long
    
        x1 = (x << 13) Xor x
    
        x2.LongValue = x1 * x1 * 15731 + 789221
        x3.LongValue = x1 * x2.IntValue + 1376312589
    
        x4 = x3.IntValue And &H7FFFFFFF
    
        Return (1.0R - x4 / 1073741824.0R)
    End Function
    

    After these changes I got the same results in VB.net and in C#.

提交回复
热议问题