예제 #1
0
	// Copy the contents of one array into another (general-purpose version).
	public static void Copy(Array sourceArray, int sourceIndex,
						    Array destinationArray,
						    int destinationIndex, int length)
	{
		// Validate the parameters.
		if(sourceArray == null)
		{
			throw new ArgumentNullException("sourceArray");
		}
		if(destinationArray == null)
		{
			throw new ArgumentNullException("destinationArray");
		}
		if(sourceArray.GetRank() != destinationArray.GetRank())
		{
			throw new RankException(_("Arg_MustBeSameRank"));
		}
		int srcLower = sourceArray.GetLowerBound(0);
		int srcLength = sourceArray.GetLength();
		int dstLower = destinationArray.GetLowerBound(0);
		int dstLength = destinationArray.GetLength();
		if(sourceIndex < srcLower)
		{
			throw new ArgumentOutOfRangeException
				("sourceIndex", _("ArgRange_Array"));
		}
		if(destinationIndex < dstLower)
		{
			throw new ArgumentOutOfRangeException
				("destinationIndex", _("ArgRange_Array"));
		}
		if(length < 0)
		{
			throw new ArgumentOutOfRangeException
				("length", _("ArgRange_NonNegative"));
		}
		int srcRelative = sourceIndex - srcLower;
		int dstRelative = destinationIndex - dstLower;
		if((srcLength - (srcRelative)) < length ||
		   (dstLength - (dstRelative)) < length)
		{
			throw new ArgumentException(_("Arg_InvalidArrayRange"));
		}

		// Get the array element types.
		Type arrayType1 = sourceArray.GetType().GetElementType();
		Type arrayType2 = destinationArray.GetType().GetElementType();

		// Is this a simple array copy of the same element type?
		if(arrayType1 == arrayType2)
		{
			InternalCopy
				(sourceArray, srcRelative,
				 destinationArray, dstRelative,
				 length);
			return;
		}

		// Check that casting between the types is possible,
		// without using a narrowing conversion.
		if(!ArrayTypeCompatible(arrayType1, arrayType2))
		{
			throw new ArrayTypeMismatchException
				(_("Exception_ArrayTypeMismatch")); 
		}

		// Copy the array contents the hard way.  We don't have to
		// worry about overlapping ranges because there is no way
		// to get here if the source and destination are the same.
		int index;
		for(index = 0; index < length; ++index)
		{
			try
			{
				destinationArray.SetRelative(
					Convert.ConvertObject(
						sourceArray.GetRelative(srcRelative + index), 
						arrayType2), dstRelative + index);
			}
			catch(FormatException e)
			{
				throw new InvalidCastException(String.Format(_("InvalidCast_FromTo"),
 						     arrayType1, arrayType2), e);
			}
		}
	}