質問

現在、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バージョンでは、必要はありません。

みんなありがとう。

役に立ちましたか?

解決

関数であるため、 getXSectorOffset の後に()を追加しますか?

例:

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

2番目の質問については、次の変更によりキャストをフロートにしないようにすることができます。

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

申し訳ありませんが、まだ int にキャストする必要があります。関数中に x および getXOffset() int にキャストしない限り:

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

他のヒント

" Dim"は使用しないでください。クラス/構造レベルの変数。常にパブリック、保護、プライベートなどを使用します。

また、VBとC#では除算の動作が異なることに注意してください。 VBでは、次のように2つの整数を分割する場合:

Dim r As Double = 5/2

その場合、rは値が2.5のDoubleになります

ただし、C#では、整数で除算すると整数の結果が得られます。この場合は2です。

VBコードで Option Strict On を設定した場合(常に常に実行する必要があります)、VBで戻り値をキャストする必要があると思います同様に:Math.Floor()はSingleではなくDoubleを返します。コンパイラーに許可するのではなく、その精度(C#バージョンの(float)キャストが行うこと)を失いたいとコンパイラーに本当に伝える必要があります。情報に基づいた決定を下さずに精度を捨ててください。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top