简体   繁体   English

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

[英]Problem while porting VB.NET Code to C#

Currently I am trying to port some VB.NET code to C#. 目前,我正在尝试将一些VB.NET代码移植到C#。

The struct looks like this in VB.NET: 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# Version of the struct: 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;
        }
    }

Why do I have to cast the return values to float & int ? 为什么我必须将返回值强制转换为float&int? In the vb version I don't have to.. 在vb版本中,我不必..

Thanks everyone. 感谢大家。

Put a () after getXSectorOffset because it's a function? ()放在getXSectorOffset之后,因为它是一个函数?

example: 例:

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

Regarding the second question, you could avoid cast to float with this modification: 关于第二个问题,您可以通过此修改避免强制转换为浮点型:

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

And sorry, you'll have to cast to int still. 很抱歉,您必须仍然强制转换为int Unless you cast the x and getXOffset() to int during the function: 除非在函数执行期间将xgetXOffset()int ,否则:

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

Note that you shouldn't use "Dim" on class/structure level variables. 请注意,您不应在类/结构级变量上使用“ Dim”。 Always use Public, Protected, Private etc. 始终使用公共,受保护,私有等。

Also note that division works differently in VB and C#. 还要注意,除法在VB和C#中的工作方式不同。 In VB, if you divide two integers like so: 在VB中,如果您将两个整数相除,如下所示:

Dim r As Double = 5/2

Then r will be a Double with value 2.5 那么r将是一个2.5的Double

In C# however, division with integers gives you integer results, 2 in this case. 但是,在C#中,用整数除法可以得到整数结果,在这种情况下为2。

如果您在VB代码中设置Option Strict On (您确实应该总是这样做),那么我认为您也需要在VB中强制转换返回值:Math.Floor()返回Double,而不是Single,并且您应该真正告诉编译器您想失去该精度(这是C#版本中的(浮点数)所做的事情),而不是让编译器在没有做出明智决定的情况下就放弃精度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM