我正在使用基于数组的扩展方法,我想知道是否有一种简单的方法来检查数组是否获得了指定的大小,而不是我复制粘贴
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发布于 2012-05-31 07:11:06
由于您的数组并不是真正的数组,而是表示一个特定的数据结构(棋盘),您是否考虑过为它创建一个专用类型?
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-31 07:18:17
您正在寻找类似如下的内容:
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-31 07:00:41
看起来你想要像这样的东西:
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);https://stackoverflow.com/questions/10825372
复制相似问题