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

由于您的数组并不是真正的数组,而是代表特定的数据结构(棋盘),您是否考虑过为其创建专用类型?

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 回答