1

配列に基づいた拡張メソッドを使用していますが、配列をコピーして貼り付ける代わりに、指定したサイズになっていることを確認する簡単な方法があるかどうかを知りたいです。

   if array.count != 1000
      throw new exception "size of the array does not match"

約 50 の拡張子で

これは私が使用している拡張機能の小さなサンプルです。

<Extension()>
Public Function IsWhite(ByVal board() As bitPiece, ByVal pos As Integer) As Boolean
    Return (board(pos) And bitPiece.White) = bitPiece.White
End Function

<Extension()>
Public Function IsBlack(ByVal board() As bitPiece, ByVal pos As Integer) As Boolean
    Return (board(pos) And bitPiece.Black) = bitPiece.Black
End Function

<Extension()>
Public Function IsRook(ByVal board() As bitPiece, ByVal pos As Integer) As Boolean
    Return (board(pos) And bitPiece.Rook) = bitPiece.Rook
End Function

<Extension()>
Public Function IsBishop(ByVal board() As bitPiece, ByVal pos As Integer) As Boolean
    Return (board(pos) And bitPiece.Bishop) = bitPiece.Bishop
End Function

<Extension()>
Public Function IsKnight(ByVal board() As bitPiece, ByVal pos As Integer) As Boolean
    Return (board(pos) And bitPiece.knight) = bitPiece.knight
End Function

<Extension()>
Public Function IsQueen(ByVal board() As bitPiece, ByVal pos As Integer) As Boolean
    Return (board(pos) And bitPiece.Queen) = bitPiece.Queen
End Function

<Extension()>
Public Function IsKing(ByVal board() As bitPiece, ByVal pos As Integer) As Boolean
    Return (board(pos) And bitPiece.King) = bitPiece.King
End Function

<Extension()>
Public Function IsPawn(ByVal board() As bitPiece, ByVal pos As Integer) As Boolean
    Return (board(pos) And bitPiece.Pawn) = bitPiece.Pawn
End Function
4

3 に答える 3

2

Since your array is not really an array but represents a specific data structure (a chess board), have you considered creating a dedicated type for it?

class Board
{
    private readonly bitPiece[] board;

    public Board()
    {
        board = new bitPiece[64];
    }

    Public Function IsBlack(ByVal pos As Integer) As Boolean
        Return (board(pos) And bitPiece.Black) = bitPiece.Black
    End Function
}
于 2012-05-30T23:11:06.200 に答える
1

あなたは次のようなものを探しています:

public static void CheckArrLength(this double[] x, int length)
    {
        if (x.Length != length)
            throw new ArgumentException("Invalid Array Size."); 
    }

そして、すべてのメソッドは次のように呼び出すことができます:

public static void Func(this double[] x)
    {
        x.CheckArrLength(1000);
        ...
    }
于 2012-05-30T23:18:16.850 に答える
0

次のようなものが必要なようです:

public static void AssertLength<T>(this T[] arr, int expectedLength)
{
    if (arr == null || arr.Length != expectedLength)
    {
        throw new Exception("Size of the array does not match");
    }
}

を使用して呼び出すことができます

new[] { 1, 2, 3 }.AssertLength(5);
于 2012-05-30T23:00:41.410 に答える