将VB.NET代码移植到C#时出现问题

时间:2009-09-10 03:29:32

标签: c# vb.net struct casting

目前我正在尝试将一些VB.NET代码移植到C#。

在VB.NET中结构如下所示:

Public Structure sPos
    Dim x, y, z As Single
    Function getSectorY() As Single
        Return Math.Floor(y / 192 + 92)
    End Function
    Function getSectorX() As Single
        Return Math.Floor(x / 192 + 135)
    End Function
    Function getSectorXOffset() As Int32
        Return ((x / 192) - getSectorX() + 135) * 192 * 10
    End Function
    Function getSectorYOffset() As Int32
        Return ((y / 192) - getSectorY() + 92) * 192 * 10
    End Function
End Structure

C#结构版本:

    public struct sPos
    {
        public float x;
        public float y;
        public float z;
        public float getSectorY()
        {
            return (float)Math.Floor(y / 192 + 92);
        }
        public float getSectorX()
        {
            return (float)Math.Floor(x / 192 + 135);
        }
        public Int32 getSectorXOffset()
        {
            return (int)((x / 192) - getSectorX() + 135) * 192 * 10;
        }
        public Int32 getSectorYOffset()
        {
            return (int)((y / 192) - getSectorY() + 92) * 192 * 10;
        }
    }

为什么我必须将返回值强制转换为float& int?在vb版本中我没有...

谢谢大家。

3 个答案:

答案 0 :(得分:2)

()之后加getXSectorOffset,因为它是一个函数?

示例:

nullPointX = pictureBox1.Width / 2 - sectorsize - centerPos.getSectorXOffset() / 10 * sectorsize / 192;

关于第二个问题,您可以通过此修改避免强制转换:

public float getSectorY()
    {
        return (float)Math.Floor(y / 192f + 92f);
    }

抱歉,你必须继续施放int。除非您在函数期间将xgetXOffset()强制转换为int

public Int32 getSectorXOffset()
    {
        return (((int)x / 192) - (int)getSectorX() + 135) * 192 * 10;
    }

答案 1 :(得分:2)

请注意,不应在类/结构级变量上使用“Dim”。始终使用公共,受保护,私人等。

另请注意,除法在VB和C#中的工作方式不同。在VB中,如果你像这样划分两个整数:

Dim r As Double = 5/2

然后r将是Double值2.5

在C#中,使用整数除法可得到整数结果,在这种情况下为2。

答案 2 :(得分:2)

如果你在VB代码中设置 Option Strict On (你真的应该总是那么做)那么我认为你需要在VB中强制转换返回值同样:Math.Floor()返回一个Double而不是Single,你应该告诉编译器你想要丢失那个精度(这是C#版本中的(float)强制转换)而不是让编译器在没有做出明智决定的情况下抛弃精确度。

相关问题