コード例 #1
0
 public MultiDimArrayNode(ObjectNode parent, Array array, string name) : base(parent, array, 0, null)
 {
     if (name == null)
     {
         this.Name = array.GetType().GetElementType().FormatTypeName() + "[,]";
     }
     else
     {
         this.Name = name;
     }
     this.ElementType = array.GetType().GetElementType();
     this.Data = array;
 }
コード例 #2
0
        public void GetData(System.Array data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (!UnsafeUtility.IsBlittable(data.GetType().GetElementType()))
            {
                throw new ArgumentException(string.Format("{0} type used in ComputeBuffer.GetData(array) must be blittable", data.GetType().GetElementType()));
            }

            InternalGetData(data, 0, 0, data.Length, Marshal.SizeOf(data.GetType().GetElementType()));
        }
コード例 #3
0
ファイル: Utils.cs プロジェクト: AndresSoacha17/VentasWeb
 public static System.Array SetLength(System.Array sArray, int size)
 {
     System.Type  t      = sArray.GetType().GetElementType();
     System.Array nArray = System.Array.CreateInstance(t, size);
     System.Array.Copy(sArray, 0, nArray, 0, Math.Min(sArray.Length, size));
     return(nArray);
 }
コード例 #4
0
 /// <summary>
 /// Fills the array with an specific value from an specific index to an specific index.
 /// </summary>
 /// <param name="array">The array to be filled.</param>
 /// <param name="fromindex">The first index to be filled.</param>
 /// <param name="toindex">The last index to be filled.</param>
 /// <param name="val">The value to fill the array with.</param>
 public static void Fill(System.Array array, System.Int32 fromindex, System.Int32 toindex, System.Object val)
 {
     System.Object Temp_Object = val;
     System.Type   elementtype = array.GetType().GetElementType();
     if (elementtype != val.GetType())
     {
         Temp_Object = Convert.ChangeType(val, elementtype);
     }
     if (array.Length == 0)
     {
         throw (new System.NullReferenceException());
     }
     if (fromindex > toindex)
     {
         throw (new System.ArgumentException());
     }
     if ((fromindex < 0) || ((System.Array)array).Length < toindex)
     {
         throw (new System.IndexOutOfRangeException());
     }
     for (int index = (fromindex > 0) ? fromindex-- : fromindex; index < toindex; index++)
     {
         array.SetValue(Temp_Object, index);
     }
 }
コード例 #5
0
ファイル: WhfEncryption.cs プロジェクト: kevin-h-wang/tuopu
 /// <summary>
 /// 重新定义一个数组列表
 /// </summary>
 /// <param name="OriginalArray">需要被重定义的数组</param>
 /// <param name="NewSize">这个数组的新大小</param>
 public static Array ReDim(Array OriginalArray, Int32 NewSize)
 {
     Type ArrayElementsType = OriginalArray.GetType().GetElementType();
     Array newArray = Array.CreateInstance(ArrayElementsType, NewSize);
     Array.Copy(OriginalArray, 0, newArray, 0, Math.Min(OriginalArray.Length, NewSize));
     return newArray;
 }
コード例 #6
0
 void ICollection.CopyTo(Array array, int index)
 {
     if (array is ThemeInfo[])
         ((ICollection)this._collection).CopyTo(array, index);
     else
         throw new InvalidCastException(String.Format("Can not cast {0} to ThemeInfo[]", array.GetType()));
 }
コード例 #7
0
            public CellArrayTemplate(System.Array p_Array)
            {
                m_Array = p_Array;
                Type l_ElementType = m_Array.GetType().GetElementType();

                DataModel = SourceGrid2.Utility.CreateDataModel(l_ElementType);
            }
コード例 #8
0
ファイル: MegaVideoDecrypter.cs プロジェクト: Hagser/csharp
 private static Array aRedimension(Array orgArray, Int32 tamaño)
 {
     Type t = orgArray.GetType().GetElementType();
     Array nArray = Array.CreateInstance(t, tamaño);
     Array.Copy(orgArray, 0, nArray, 0, Math.Min(orgArray.Length, tamaño));
     return nArray;
 }
コード例 #9
0
ファイル: Arrays.cs プロジェクト: cole2295/nfx
        public static string ArrayToDescriptor(Array array, 
            TypeRegistry treg,
            Type type = null,
            string th = null)
        {
            if (type==null)
                 type = array.GetType();

              if (array.LongLength>MAX_ELM_COUNT)
                throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_ELM_ERROR.Args(array.LongLength, MAX_ELM_COUNT));

              if (type==typeof(object[]))//special case for object[], because this type is very often used in Glue and other places
               return "$1|"+array.Length.ToString();

              if (th==null)
                 th = treg.GetTypeHandle(type);

               var ar = array.Rank;
               if (ar>MAX_DIM_COUNT)
                throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_DIMS_ERROR.Args(ar, MAX_DIM_COUNT));

               var descr = new StringBuilder(th);
               descr.Append('|');//separator char

               for(int i=0; i<ar; i++)
               {
                  descr.Append(array.GetLowerBound(i));
                  descr.Append('~');
                  descr.Append(array.GetUpperBound(i));
                  if (i<ar-1)
                   descr.Append(',');
               }

              return descr.ToString();
        }
コード例 #10
0
      /// <summary>
      /// This factory method wraps a SafePinnedObject around the specified array.
      /// </summary>
      /// <param name="array">The array that you want to pin.</param>
      /// <param name="startOffset">The first element in the array whose address you want to pass to native code.</param>
      /// <param name="numberOfElements">The number of elements in the array you wish to pass to native code.</param>
      /// <returns>The SafePinnedObject wrapping the desired array elements.</returns>
      public static SafePinnedObject FromArray(Array array, Int32 startOffset, Int32 numberOfElements) {
         // If obj is null, we create this object but it pins nothing (size will be 0)
         if (array == null) return new SafePinnedObject(null, 0, 0);

         // Validate the structure of the object before pinning it
         if (array.Rank != 1)
            throw new ArgumentException("array Rank must be 1");

         if (startOffset < 0)
            throw new ArgumentOutOfRangeException("startOffset", "Must be >= 0");

         // Validate the structure of the array's element type
         Type elementType = array.GetType().GetElementType();
         if (!elementType.IsValueType && !elementType.IsEnum)
            throw new ArgumentException("array's elements must be value types or enum types");

         if (elementType.IsAutoLayout)
            throw new ArgumentException("array's elements must not be auto layout");

         // If numElements not specied (-1), assume the remainder of the array length
         if (numberOfElements == -1) numberOfElements = array.Length - startOffset;

         if (numberOfElements > array.Length)
            throw new ArgumentOutOfRangeException("numberOfElements", "Array has fewer elements than specified");

         // Convert startOffset from element offset to byte offset
         startOffset *= Marshal.SizeOf(elementType);

         return new SafePinnedObject(array, startOffset, 
            numberOfElements * Marshal.SizeOf(elementType));  // Convert numElements to number of bytes
      }
コード例 #11
0
 public static string CodeRepresentation(Array a)
 {
     StringBuilder ret = new StringBuilder();
     ret.Append(a.GetType().FullName);
     ret.Append("(");
     switch (a.Rank) {
         case 1: {
                 for (int i = 0; i < a.Length; i++) {
                     if (i > 0) ret.Append(", ");
                     ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0))));
                 }
             }
             break;
         case 2: {
                 int imax = a.GetLength(0);
                 int jmax = a.GetLength(1);
                 for (int i = 0; i < imax; i++) {
                     ret.Append("\n");
                     for (int j = 0; j < jmax; j++) {
                         if (j > 0) ret.Append(", ");
                         ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0), j + a.GetLowerBound(1))));
                     }
                 }
             }
             break;
         default:
             ret.Append(" Multi-dimensional array ");
             break;
     }
     ret.Append(")");
     return ret.ToString();
 }
コード例 #12
0
ファイル: Utils.cs プロジェクト: yan6pz/MovieRecommendation
		public static bool ArrayDeepEquals(Array arr1, Array arr2) {
			if (arr1.Length!=arr2.Length || arr1.GetType()!=arr2.GetType())
				return false;

			for (int i=0; i<arr1.Length; i++) {
				var v1 = arr1.GetValue(i);
				var v2 = arr2.GetValue(i);
				if (v1 is Array && v2 is Array)
					if (!ArrayDeepEquals((Array)v1, (Array)v2)) {
						return false;
					} else
						continue;

				if (v1==null && v2==null)
					continue;

				if (v1!=null)
					if (!v1.Equals(v2))
						return false;
				if (v2 != null)
					if (!v2.Equals(v1))
						return false;
			}
			return true;
		}
コード例 #13
0
ファイル: ArrayExtension.cs プロジェクト: GirlD/mono
		public ArrayExtension (Array elements)
		{
			if (elements == null)
				throw new ArgumentNullException ("elements");
			Type = elements.GetType ().GetElementType ();
			items = new ArrayList (elements);
		}
コード例 #14
0
ファイル: System_Array.cs プロジェクト: randomize/ERP_Coding
    private static int __newindex_Array(ILuaState L)
    {
        System.Array obj = L.ChkUserDataSelf(1, CLASS) as System.Array;

        if (obj == null)
        {
            L.L_Error("trying to newindex an invalid Array reference");
            return(0);
        }

        int    index   = L.ChkInteger(2);
        object val     = L.ToAnyObject(3);
        var    valType = val.GetType();

        System.Type type = obj.GetType().GetElementType();

        if (!type.IsAssignableFrom(valType))
        {
            L.L_Error(string.Format("trying to set object type is not correct: {0} expected, got {1}", type, valType));
            return(0);
        }

        val = System.Convert.ChangeType(val, type);
        obj.SetValue(val, index);

        return(0);
    }
コード例 #15
0
        //This will contain the data in parsed form.

        public static System.Array resizeArray(System.Array oldArray, int newSize)  // this function will resize our temporary string array that is used to store the parsed Line.
        {
            int oldSize = oldArray.Length;

            System.Type  elementType = oldArray.GetType().GetElementType();
            System.Array newArray    = System.Array.CreateInstance(elementType, newSize);
            return(newArray);
        }
コード例 #16
0
ファイル: ObjectFormatters.cs プロジェクト: glorylee/Aoite
        private static void WriteSimpleArray(this ObjectWriter writer, Array value)
        {
            writer.WriteTag(FormatterTag.Array);

            var elementType = value.GetType().GetElementType();
            writer.InnerWrite(elementType);
            writer.InnerWrite(value);
        }
コード例 #17
0
ファイル: ArrayExtension.cs プロジェクト: stabbylambda/mono
		public ArrayExtension (Array elements)
		{
			if (elements == null)
				throw new ArgumentNullException ("elements");
			Type = elements.GetType ().GetElementType ();
			Items = new List<object> (elements.Length);
			foreach (var o in elements)
				Items.Add (o);
		}
コード例 #18
0
        public void GetData(System.Array data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            InternalGetData(data, 0, 0, data.Length, Marshal.SizeOf(data.GetType().GetElementType()));
        }
コード例 #19
0
ファイル: ArrayUtils.cs プロジェクト: kbatoev/VSharp
        public static void ClearInternal(object thisNull, System.Array array, int index, int length)
        {
            index += array.GetLowerBound(0);
            object defaultValue = Activator.CreateInstance(array.GetType().GetElementType());

            for (var ind = index; ind < length; ind++)
            {
                array.SetValue(defaultValue, ind);
            }
        }
コード例 #20
0
        //---------------------------------------------------------------
        #endregion
        //---------------------------------------------------------------

        //---------------------------------------------------------------
        #region Methods
        //---------------------------------------------------------------
        /// <summary>
        /// Serializes the given object.
        /// </summary>
        /// <param name="obj">The object to serialize.</param>
        /// <param name="stream">Stream to fill with data.</param>
        public void Serialize(object obj, SerializeStream stream)
        {
            stream.Write("elementType", array.GetType().GetElementType());
            stream.Write("length", array.Length);
            for (int i = 0; i < array.Length; i++)
            {
                object value = array.GetValue(i);
                stream.WriteAsObject(null, value);
            }
        }
コード例 #21
0
 public ArrayExtension(Array elements)
 {
     this.arrayElementList = new ArrayList();
     if (elements == null)
     {
         throw new ArgumentNullException("elements");
     }
     this.arrayElementList.AddRange(elements);
     this.arrayType = elements.GetType().GetElementType();
 }
コード例 #22
0
ファイル: Utils.cs プロジェクト: mrecht/qSharp
        /// <summary>
        ///     Compares to arrays for values equality.
        /// </summary>
        /// <returns>true if both arrays contain the same values, false otherwise</returns>
        internal static bool ArrayEquals(Array l, Array r)
        {
            if (l == null && r == null)
            {
                return true;
            }

            if (l == null || r == null)
            {
                return false;
            }

            if (l.GetType() != r.GetType())
            {
                return false;
            }

            if (l.Length != r.Length)
            {
                return false;
            }

            for (var i = 0; i < l.Length; i++)
            {
                var lv = l.GetValue(i);
                var rv = r.GetValue(i);

                if (lv == rv || lv == null && rv == null)
                {
                    continue;
                }

                if (lv == null || rv == null)
                {
                    return false;
                }

                if (lv.GetType().IsArray)
                {
                    if (!ArrayEquals(lv as Array, rv as Array))
                    {
                        return false;
                    }
                }
                else
                {
                    if (!lv.Equals(rv))
                    {
                        return false;
                    }
                }
            }

            return true;
        }
コード例 #23
0
        private static void AssertImport(Array expected, string s)
        {
            JsonReader reader = CreateReader(s);
            
            object o = reader.Get(expected.GetType());

            if (expected == null)
                Assert.IsNull(o);
            
            Assert.AreEqual(expected, o);
        }
コード例 #24
0
 ///Resize array of arbitrary element type. Creates a new instance.
 public static System.Array Resize(this System.Array array, int newSize) {
     if ( array == null ) { return null; }
     var oldSize = array.Length;
     var elementType = array.GetType().GetElementType();
     var newArray = System.Array.CreateInstance(elementType, newSize);
     var preserveLength = System.Math.Min(oldSize, newSize);
     if ( preserveLength > 0 ) {
         System.Array.Copy(array, newArray, preserveLength);
     }
     return newArray;
 }
コード例 #25
0
 /// <summary>
 /// 重定义数组
 /// </summary>
 /// <param name="origArray">原来的数组长度</param>
 /// <param name="desiredsize">新的宽度</param>
 /// <returns></returns>
 public static Array Redim(Array origArray, Int32 desiredsize)
 {
     //确定每个元素类型           
     Type t = origArray.GetType().GetElementType();
     //创建一个含有期望元素个数的新数组       
     //新数组的类型必须匹配原数组的类型       
     Array newArray = Array.CreateInstance(t, desiredsize);
     //将原数组中的元素拷贝到新数组中       
     Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, desiredsize));
     return newArray;
 }
コード例 #26
0
ファイル: CXmlDriverEngine.cs プロジェクト: jmhardison/corefx
        private static Array CombineArrays(Array arr1, Array arr2)
        {
            if (arr1 == null)
                return arr2;
            if (arr2 == null)
                return arr1;

            Array newArr = Array.CreateInstance(arr1.GetType().GetElementType(), arr1.Length + arr2.Length);
            arr1.CopyTo(newArr, 0);
            arr2.CopyTo(newArr, arr1.Length);
            return newArr;
        }
コード例 #27
0
        private static PropertyDescriptorCollection CreateColumnPropertyDescriptorCollection(Array source)
        {
            var elementType = source.GetType().GetElementType();
            var n = source.GetLength(0);
            var descriptors = new Array2DIndexPropertyDescriptor[n];
            for (int i = 0; i < n; i++)
            {
                descriptors[i] = new Array2DIndexPropertyDescriptor(elementType, i);
            }

            return new PropertyDescriptorCollection(descriptors);
        }
コード例 #28
0
ファイル: Buffer.cs プロジェクト: nguyenkien/api
		public static int ByteLength (Array array)
		{
			if (array == null)throw new ArgumentNullException ("array");

            if (array.Length == 0) return 0;

		    var type = array.GetType().GetElementType();

            if (!type.IsPrimitive)throw new ArgumentException ("Object must be an array of primitives.");

            return array.Length * NumberOfBytesForPrimitiveType (type);
		}
コード例 #29
0
        protected Array resizeArray(Array oldArray, int newSize)
        {
            int oldSize = oldArray.Length;
            Type elementType = oldArray.GetType().GetElementType();
            System.Array newArray = System.Array.CreateInstance(elementType, newSize);
            int preserveLength = System.Math.Min(oldSize, newSize);
            if (preserveLength > 0)
                System.Array.Copy(oldArray, newArray, preserveLength);


            return newArray;
        }
コード例 #30
0
	// Validate a primitive array and get its length in bytes.
	private static int ValidatePrimitive(Array array, String name)
			{
				if(array == null)
				{
					throw new ArgumentNullException(name);
				}
				else if(!array.GetType().GetElementType().IsPrimitive)
				{
					throw new ArgumentException
						(_("Arg_NonPrimitiveArray"), name);
				}
				return GetLength(array);
			}
コード例 #31
0
ファイル: ArrayExtension.cs プロジェクト: spencerhakim/mono
		public ArrayExtension (Array elements)
		{
			if (elements == null)
				throw new ArgumentNullException ("elements");
			Type = elements.GetType ().GetElementType ();
#if MOONLIGHT
			items = new List<object> ();
			foreach (var element in elements)
				items.Add (element);
#else
			items = new ArrayList (elements);
#endif
		}
コード例 #32
0
        public static Array Add(Array data1, Array data2)
        {
            if (data1.Rank > 1 || data2.Rank > 1) throw new NotImplementedException("can't add multidimensional arrays");

            Type type1 = data1.GetType();
            Type type2 = data2.GetType();
            Type type = (type1 == type2) ? type1.GetElementType() : typeof(object);

            Array ret = Array.CreateInstance(type, data1.Length + data2.Length);
            Array.Copy(data1, 0, ret, 0, data1.Length);
            Array.Copy(data2, 0, ret, data1.Length, data2.Length);
            return ret;
        }
コード例 #33
0
        private static PropertyDescriptorCollection CreateRowPropertyDescriptorCollection(Array source)
        {
            var elementType = source.GetType().GetElementType();
            var n = source.GetLength(1);
            var descriptors = new Array2DIndexPropertyDescriptor[n];
            for (int i = 0; i < n; i++)
            {
                descriptors[i] = new Array2DIndexPropertyDescriptor(elementType, i);
            }

            // ReSharper disable once CoVariantArrayConversion
            return new PropertyDescriptorCollection(descriptors);
        }
コード例 #34
0
    XmlElement CreateElementFromArray(System.Array array, string fieldname)
    {
        XmlElement xmlElement = xmlDoc.CreateElement(fieldname);

        if (array.GetType() == typeof(System.Single[]))
        {
            System.Single[] floats = array as float[];
            for (int i = 0; i < floats.Length; i++)
            {
                xmlElement.SetAttribute("array" + i.ToString(), floats[i].ToString());
            }
        }
        else if (array.GetType() == typeof(System.String[]))
        {
            System.String[] strings = array as System.String[];
            for (int i = 0; i < strings.Length; i++)
            {
                xmlElement.SetAttribute("array" + i.ToString(), strings[i]);
            }
        }
        return(xmlElement);
    }
コード例 #35
0
ファイル: Flatten_array.cs プロジェクト: ralfw/Equalidator
 internal void Iterate_array_elements_in_all_dimensions(Array objectToFlatten, List<int> indexes)
 {
     var t = objectToFlatten.GetType();
     if (t.GetArrayRank() > indexes.Count)
         for (var i = 0; i < objectToFlatten.GetLength(indexes.Count); i++)
         {
             indexes.Add(i);
             Iterate_array_elements_in_all_dimensions(objectToFlatten, indexes);
             indexes.RemoveAt(indexes.Count - 1);
         }
     else
         this.Element(objectToFlatten.GetValue(indexes.ToArray()));
 }
コード例 #36
0
        public static int ArrayNewIndexer(RealStatePtr L)
#endif
        {
            try
            {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
                System.Array     array      = (System.Array)translator.FastGetCSObj(L, 1);

                if (array == null)
                {
                    return(LuaAPI.luaL_error(L, "#1 parameter is not a array!"));
                }

                int i = LuaAPI.xlua_tointeger(L, 2);

                if (i >= array.Length)
                {
                    return(LuaAPI.luaL_error(L, "index out of range! i =" + i + ", array.Length=" + array.Length));
                }

                Type type = array.GetType();
                if (TryPrimitiveArraySet(type, L, array, i, 3))
                {
                    return(0);
                }

                if (InternalGlobals.genTryArraySetPtr != null)
                {
                    try
                    {
                        if (InternalGlobals.genTryArraySetPtr(type, L, translator, array, i, 3))
                        {
                            return(0);
                        }
                    }
                    catch (Exception e)
                    {
                        return(LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace));
                    }
                }

                object val = translator.GetObject(L, 3, type.GetElementType());
                array.SetValue(val, i);

                return(0);
            }
            catch (Exception e)
            {
                return(LuaAPI.luaL_error(L, "c# exception in ArrayNewIndexer:" + e));
            }
        }
コード例 #37
0
        /// <summary>
        /// Reallocates an array with a new size, and copies the contents
        /// of the old array to the new array.
        /// </summary>
        /// <param name="oldArray">The old array, to be reallocated.</param>
        /// <param name="newSize">The new array size.</param>
        /// <returns>A new array with the same contents.</returns>
        /// <remarks >Useage: int[] a = {1,2,3}; a = (int[])ResizeArray(a,5);</remarks>
        public static System.Array ResizeArray(System.Array oldArray, int newSize)
        {
            int oldSize = oldArray.Length;

            System.Type  elementType    = oldArray.GetType().GetElementType();
            System.Array newArray       = System.Array.CreateInstance(elementType, newSize);
            int          preserveLength = System.Math.Min(oldSize, newSize);

            if (preserveLength > 0)
            {
                System.Array.Copy(oldArray, newArray, preserveLength);
            }
            return(newArray);
        }
コード例 #38
0
        public static int ArrayIndexer(RealStatePtr L)
        {
            try
            {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
                System.Array     array      = (System.Array)translator.FastGetCSObj(L, 1);

                if (array == null)
                {
                    return(LuaAPI.luaL_error(L, "#1 parameter is not a array!"));
                }

                int i = LuaAPI.xlua_tointeger(L, 2);

                if (i >= array.Length)
                {
                    return(LuaAPI.luaL_error(L, "index out of range! i =" + i + ", array.Length=" + array.Length));
                }

                Type type = array.GetType();
                if (tryPrimitiveArrayGet(type, L, array, i))
                {
                    return(1);
                }

                if (genTryArrayGetPtr != null)
                {
                    try
                    {
                        if (genTryArrayGetPtr(type, L, translator, array, i))
                        {
                            return(1);
                        }
                    }
                    catch (Exception e)
                    {
                        return(LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace));
                    }
                }

                object ret = array.GetValue(i);
                translator.PushAny(L, ret);

                return(1);
            }
            catch (Exception e)
            {
                return(LuaAPI.luaL_error(L, "c# exception in ArrayIndexer:" + e));
            }
        }
コード例 #39
0
ファイル: Parser.cs プロジェクト: mtswiss/UniWork
        //This will contain the data in parsed form.

        public static System.Array resizeArray(System.Array oldArray)  // this function will resize our temporary string array that is used to store the parsed Line.
        {
            int oldSize = oldArray.Length;

            System.Type  elementType = oldArray.GetType().GetElementType();
            System.Array newArray    = System.Array.CreateInstance(elementType, 16);
            //now we'll copy the contents of the old array into the new array
            for (int i = 0; i < oldArray.Length; ++i)
            {
                newArray.SetValue(oldArray.GetValue(i), i);
            }
            newArray.SetValue("", 15);
            return(newArray);
        }
コード例 #40
0
ファイル: ArrayOps.cs プロジェクト: CookieEaters/FireHTTP
        public static Array Add(Array data1, Array data2) {
            if (data1 == null) throw PythonOps.TypeError("expected array for 1st argument, got None");
            if (data2 == null) throw PythonOps.TypeError("expected array for 2nd argument, got None");

            if (data1.Rank > 1 || data2.Rank > 1) throw new NotImplementedException("can't add multidimensional arrays");

            Type type1 = data1.GetType();
            Type type2 = data2.GetType();
            Type type = (type1 == type2) ? type1.GetElementType() : typeof(object);

            Array ret = Array.CreateInstance(type, data1.Length + data2.Length);
            Array.Copy(data1, 0, ret, 0, data1.Length);
            Array.Copy(data2, 0, ret, data1.Length, data2.Length);
            return ret;
        }
コード例 #41
0
ファイル: CommonTools.cs プロジェクト: sandatan/reportsmart
        public static System.Array ResizeArray(System.Array aArray, int aSize)
        {
            int lSize = aArray.Length;

            System.Type  lType    = aArray.GetType().GetElementType();
            System.Array Result   = System.Array.CreateInstance(lType, aSize);
            int          lPLength = System.Math.Min(aSize, lSize);

            if (lPLength > 0)
            {
                System.Array.Copy(aArray, Result, lPLength);
            }

            return(Result);
        }
コード例 #42
0
ファイル: Util.cs プロジェクト: priceLiu/fastDFS
 /// <summary>
 /// Fills the array with an specific value from an specific index to an specific index.
 /// </summary>
 /// <param _name="array">The array to be filled.</param>
 /// <param _name="fromindex">The first index to be filled.</param>
 /// <param _name="toindex">The last index to be filled.</param>
 /// <param _name="val">The value to fill the array with.</param>
 public static void Fill(Array array, Int32 fromindex, Int32 toindex, Object val)
 {
     Object temp = val;
     Type elementtype = array.GetType().GetElementType();
     if (elementtype != val.GetType())
         temp = Convert.ChangeType(val, elementtype);
     if (array.Length == 0)
         throw (new NullReferenceException());
     if (fromindex > toindex)
         throw (new ArgumentException());
     if ((fromindex < 0) || (array).Length < toindex)
         throw (new IndexOutOfRangeException());
     for (int index = (fromindex > 0) ? fromindex-- : fromindex; index < toindex; index++)
         array.SetValue(temp, index);
 }
コード例 #43
0
        [System.Security.SecuritySafeCritical] // due to Marshal.SizeOf
        public void SetData(System.Array data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (!UnsafeUtility.IsArrayBlittable(data))
            {
                throw new ArgumentException(
                          string.Format("Array passed to GraphicsBuffer.SetData(array) must be blittable.\n{0}",
                                        UnsafeUtility.GetReasonForArrayNonBlittable(data)));
            }

            InternalSetData(data, 0, 0, data.Length, UnsafeUtility.SizeOf(data.GetType().GetElementType()));
        }
コード例 #44
0
        /// <summary>
        /// Build array item bindings for the particular array.
        /// </summary>
        public IArrayItemBinding[] CreateArrayBindings(Array array)
        {
            Argument.NotNull(() => array);

            var childPropertyBindings = new List<IArrayItemBinding>();
            var objType = array.GetType();

            int i = 0;

            foreach (var item in array)
            {
                childPropertyBindings.Add(CreateArrayBinding(item, i, array));

                ++i;
            }

            return childPropertyBindings.ToArray();
        }
コード例 #45
0
		/// <summary>
		/// Concatenates two arrays.
		/// </summary>
		/// <param name="l">Left array</param>
		/// <param name="r">Right array</param>
		/// <returns>Array containing both left and right arrays.</returns>
		public static Array ConcatenateArrays(Array l, Array r) 
		{
			if (l == null)
			{
				throw new ArgumentNullException("l");
			}
			if (r == null)
			{
				throw new ArgumentNullException("r");
			}

			int len = l.Length + r.Length;
			Array a = Array.CreateInstance(l.GetType(), len);

			Array.Copy(l, 0, a, 0, l.Length);
			Array.Copy(r, 0, a, l.Length, r.Length);

			return a;
		}
コード例 #46
0
ファイル: Diag.cs プロジェクト: genxinzou/svn-spring-archive
 public static object GetArraySlice( Array inputarray, int sliceindex )
 {
     int numoutputdimensions = inputarray.Rank - 1;
     int[] newdimensions = new int[ numoutputdimensions ];
     for( int i = 1; i < numoutputdimensions + 1; i++ )
     {
         newdimensions[ i - 1 ] = inputarray.GetUpperBound( i ) + 1;
     }
     Array newarray = Array.CreateInstance( inputarray.GetType().GetElementType(), newdimensions );
     
     int[]traverseinputindex = new int[ numoutputdimensions + 1 ];
     int[]traverseoutputindex = new int[ numoutputdimensions ];
     traverseinputindex[0] = sliceindex;
     bool bDone = false;
     while( !bDone )
     {
         newarray.SetValue( inputarray.GetValue( traverseinputindex ), traverseoutputindex );
         bool bUpdatedtraverseindex = false;
         for( int i = numoutputdimensions - 1; i >= 0 && !bUpdatedtraverseindex; i-- )
         {
             traverseinputindex[i + 1]++;
             traverseoutputindex[i]++;
             if( traverseoutputindex[i] >= newdimensions[i] )
             {
                 if( i == 0 )
                 {
                     bDone = true;
                 }
                 else
                 {
                     traverseinputindex[i + 1] = 0;
                     traverseoutputindex[i ] = 0; 
                 }
             }
             else
             {
                 bUpdatedtraverseindex = true;
             }
         }
     }
     
     return newarray;
 }
コード例 #47
0
        public void GetData(System.Array data, int managedBufferStartIndex, int computeBufferStartIndex, int count)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (!UnsafeUtility.IsBlittable(data.GetType().GetElementType()))
            {
                throw new ArgumentException(string.Format("{0} type used in ComputeBuffer.GetData(array) must be blittable", data.GetType().GetElementType()));
            }

            if (managedBufferStartIndex < 0 || computeBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Length)
            {
                throw new ArgumentOutOfRangeException(String.Format("Bad indices/count argument (managedBufferStartIndex:{0} computeBufferStartIndex:{1} count:{2})", managedBufferStartIndex, computeBufferStartIndex, count));
            }

            InternalGetData(data, managedBufferStartIndex, computeBufferStartIndex, count, Marshal.SizeOf(data.GetType().GetElementType()));
        }
コード例 #48
0
ファイル: Helper.cs プロジェクト: nicogis/Surface-Utility-SOE
        /// <summary>
        /// TRANSPOSE ARRAY
        /// </summary>
        /// <param name="pixelblock">PixelBlock of data values</param>
        /// <param name="noDataValue">Default NoData value</param>
        /// <returns>Array of values transposed</returns>
        internal static Array TransposeArray(IPixelBlock3 pixelblock, object noDataValue)
        {
            System.Array oldArray = (System.Array)pixelblock.get_PixelData(0);
            int          cols     = oldArray.GetLength(0);
            int          rows     = oldArray.GetLength(1);

            System.Array newArray = System.Array.CreateInstance(oldArray.GetType().GetElementType(), rows, cols);
            for (int col = 0; col < cols; col++)
            {
                for (int row = 0; row < rows; row++)
                {
                    object noDataMaskValue = pixelblock.GetNoDataMaskVal(0, col, row);
                    object pixelValue      = (Convert.ToByte(noDataMaskValue, CultureInfo.InvariantCulture) == 1) ? oldArray.GetValue(col, row) : noDataValue;
                    newArray.SetValue(pixelValue, row, col);
                }
            }

            return(newArray);
        }
コード例 #49
0
        protected override Location <TItem> Execute(CodeActivityContext context)
        {
            System.Array array = this.Array.Get(context);
            if (array == null)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.MemberCannotBeNull("Array", base.GetType().Name, base.DisplayName)));
            }
            Type elementType = array.GetType().GetElementType();

            if (!TypeHelper.AreTypesCompatible(typeof(TItem), elementType))
            {
                throw FxTrace.Exception.AsError(new InvalidCastException(System.Activities.SR.IncompatibleTypeForMultidimensionalArrayItemReference(typeof(TItem).Name, elementType.Name)));
            }
            int[] indices = new int[this.Indices.Count];
            for (int i = 0; i < this.Indices.Count; i++)
            {
                indices[i] = this.Indices[i].Get(context);
            }
            return(new MultidimensionArrayLocation <TItem>(array, indices));
        }
コード例 #50
0
        public override void fromObject(ITarget target, object dat)
        {
            if (valueType == ValueType.Array)
            {
                System.Array arr = (System.Array)dat;
                lsArray = new List <EventData>(arr.Length);
                System.Type t = arr.GetType().GetElementType();
                for (int i = 0; i < arr.Length; i++)
                {
                    object arrElem = arr.GetValue(i);

                    EventData a = new EventData();
                    a.setValueType(arrElem != null ? arrElem.GetType() : t);
                    a.fromObject(target, arrElem);
                    lsArray.Add(a);
                }
            }
            else
            {
                base.fromObject(target, dat);
            }
        }
コード例 #51
0
ファイル: ArrayHelpers.cs プロジェクト: fubar-coder/CSFtp
        public static Array Add(Array aFirst, Array aSecond)
        {
            if (aFirst ==  null)
            {
                return aSecond.Clone() as Array;
            }

            if (aSecond == null)
            {
                return aFirst.Clone() as Array;
            }

            Type typeFirst = aFirst.GetType().GetElementType();
            Type typeSecond = aSecond.GetType().GetElementType();

            System.Diagnostics.Debug.Assert(typeFirst == typeSecond);

            Array aNewArray = Array.CreateInstance(typeFirst, aFirst.Length + aSecond.Length);
            aFirst.CopyTo(aNewArray, 0);
            aSecond.CopyTo(aNewArray, aFirst.Length);

            return aNewArray;
        }
コード例 #52
0
ファイル: DictionaryBase.cs プロジェクト: yiqideren/ice
        public void CopyTo(System.Array a__, int index)
        {
            if (a__ == null)
            {
                throw new ArgumentNullException("a__", "Cannot copy to null array");
            }
            if (index < 0)
            {
                throw new ArgumentException("Array index cannot be less than zero", "index");
            }
            if (index >= a__.Length)
            {
                throw new ArgumentException("Array index must less than array length");
            }
            if (dict_.Count > a__.Length - index)
            {
                throw new ArgumentException("Insufficient room in target array beyond index");
            }
            if (a__.Rank > 1)
            {
                throw new ArgumentException("Cannot copy to multidimensional array", "a__");
            }
            Type t = a__.GetType().GetElementType();

            if (!t.IsAssignableFrom(typeof(System.Collections.DictionaryEntry)))
            {
                throw new ArgumentException("Cannot assign DictionaryEntry to target array", "a__");
            }

            IEnumerator <KeyValuePair <KT, VT> > e = dict_.GetEnumerator();

            while (e.MoveNext())
            {
                a__.SetValue(new System.Collections.DictionaryEntry(e.Current.Key, e.Current.Value), index++);
            }
        }
コード例 #53
0
ファイル: Buffer.cs プロジェクト: steinn/mono
 static bool IsPrimitiveTypeArray(Array array)
 {
     // TODO: optimize
     return(array.GetType().GetElementType().IsPrimitive);
 }
コード例 #54
0
        // Copies from one primitive array to another primitive array without
        // respecting types.  This calls memmove internally.  The count and
        // offset parameters here are in bytes.  If you want to use traditional
        // array element indices and counts, use Array.Copy.
        public static unsafe void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count)
        {
            if (src == null)
            {
                throw new ArgumentNullException(nameof(src));
            }
            if (dst == null)
            {
                throw new ArgumentNullException(nameof(dst));
            }

            nuint uSrcLen = (nuint)src.LongLength;

            if (src.GetType() != typeof(byte[]))
            {
                if (!IsPrimitiveTypeArray(src))
                {
                    throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(src));
                }
                uSrcLen *= (nuint)src.GetElementSize();
            }

            nuint uDstLen = uSrcLen;

            if (src != dst)
            {
                uDstLen = (nuint)dst.LongLength;
                if (dst.GetType() != typeof(byte[]))
                {
                    if (!IsPrimitiveTypeArray(dst))
                    {
                        throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(dst));
                    }
                    uDstLen *= (nuint)dst.GetElementSize();
                }
            }

            if (srcOffset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(srcOffset), SR.ArgumentOutOfRange_MustBeNonNegInt32);
            }
            if (dstOffset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(dstOffset), SR.ArgumentOutOfRange_MustBeNonNegInt32);
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_MustBeNonNegInt32);
            }

            nuint uCount     = (nuint)count;
            nuint uSrcOffset = (nuint)srcOffset;
            nuint uDstOffset = (nuint)dstOffset;

            if ((uSrcLen < uSrcOffset + uCount) || (uDstLen < uDstOffset + uCount))
            {
                throw new ArgumentException(SR.Argument_InvalidOffLen);
            }

            Memmove(ref Unsafe.AddByteOffset(ref dst.GetRawArrayData(), uDstOffset), ref Unsafe.AddByteOffset(ref src.GetRawArrayData(), uSrcOffset), uCount);
        }
コード例 #55
0
        public void Write(System.Array val, int offset)
        {
            int count = Marshal.SizeOf(val.GetType().GetElementType()) * val.Length;

            Write(val, offset, count);
        }
コード例 #56
0
ファイル: Array.cs プロジェクト: lenkasetGitHub/mono
        private static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable)
        {
            if (sourceArray == null)
            {
                throw new ArgumentNullException(nameof(sourceArray));
            }

            if (destinationArray == null)
            {
                throw new ArgumentNullException(nameof(destinationArray));
            }

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), "Value has to be >= 0.");
            }

            if (sourceArray.Rank != destinationArray.Rank)
            {
                throw new RankException(SR.Rank_MultiDimNotSupported);
            }

            if (sourceIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(sourceIndex), "Value has to be >= 0.");
            }

            if (destinationIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(destinationIndex), "Value has to be >= 0.");
            }

            if (FastCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length))
            {
                return;
            }

            int source_pos = sourceIndex - sourceArray.GetLowerBound(0);
            int dest_pos   = destinationIndex - destinationArray.GetLowerBound(0);

            if (source_pos < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(sourceIndex), "Index was less than the array's lower bound in the first dimension.");
            }

            if (dest_pos < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(destinationIndex), "Index was less than the array's lower bound in the first dimension.");
            }

            // re-ordered to avoid possible integer overflow
            if (source_pos > sourceArray.Length - length)
            {
                throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
            }

            if (dest_pos > destinationArray.Length - length)
            {
                throw new ArgumentException("Destination array was not long enough. Check destIndex and length, and the array's lower bounds", nameof(destinationArray));
            }

            Type src_type    = sourceArray.GetType().GetElementType();
            Type dst_type    = destinationArray.GetType().GetElementType();
            var  dst_type_vt = dst_type.IsValueType;

            if (src_type.IsEnum)
            {
                src_type = Enum.GetUnderlyingType(src_type);
            }
            if (dst_type.IsEnum)
            {
                dst_type = Enum.GetUnderlyingType(dst_type);
            }

            if (reliable)
            {
                if (!dst_type.Equals(src_type))
                {
                    throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
                }
            }
            else
            {
                if (!CanAssignArrayElement(src_type, dst_type))
                {
                    throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
                }
            }

            if (!Object.ReferenceEquals(sourceArray, destinationArray) || source_pos > dest_pos)
            {
                for (int i = 0; i < length; i++)
                {
                    Object srcval = sourceArray.GetValueImpl(source_pos + i);

                    if (srcval == null && dst_type_vt)
                    {
                        throw new InvalidCastException();
                    }

                    try {
                        destinationArray.SetValueImpl(srcval, dest_pos + i);
                    } catch (ArgumentException) {
                        throw CreateArrayTypeMismatchException();
                    }
                }
            }
            else
            {
                for (int i = length - 1; i >= 0; i--)
                {
                    Object srcval = sourceArray.GetValueImpl(source_pos + i);

                    try {
                        destinationArray.SetValueImpl(srcval, dest_pos + i);
                    } catch (ArgumentException) {
                        throw CreateArrayTypeMismatchException();
                    }
                }
            }
        }
コード例 #57
0
ファイル: EditorGUIUtils.cs プロジェクト: mugabi0978/kinect
    private static void ObjectGUI(ref object obj, Type type, GUIContent guiContent, bool shouldDisplay, bool isReadOnly, int maxDepth, List <bool> foldoutInfo, ref int foldoutIndex)
    {
        if (type == typeof(float))
        {
            if (shouldDisplay == true)
            {
                float newValue = EditorGUILayout.FloatField(guiContent, (float)obj);
                if (isReadOnly == false && newValue != (float)obj)
                {
                    RegisterUndo();
                    obj = newValue;
                }
            }
        }
        else if (type == typeof(int))
        {
            if (shouldDisplay == true)
            {
                int newValue = EditorGUILayout.IntField(guiContent, (int)obj);
                if (isReadOnly == false && newValue != (int)obj)
                {
                    RegisterUndo();
                    obj = newValue;
                }
            }
        }
        else if (type == typeof(string))
        {
            if (shouldDisplay == true)
            {
                string newValue = EditorGUILayout.TextField(guiContent, (string)obj);
                if (isReadOnly == false && newValue != (string)obj)
                {
                    RegisterUndo();
                    obj = newValue;
                }
            }
        }
        else if (type == typeof(bool))
        {
            if (shouldDisplay == true)
            {
                bool newValue = EditorGUILayout.Toggle(guiContent, (bool)obj);
                if (isReadOnly == false && newValue != (bool)obj)
                {
                    RegisterUndo();
                    obj = newValue;
                }
            }
        }
        else if (type.IsEnum)
        {
            if (shouldDisplay == true)
            {
                Enum newValue = EditorGUILayout.EnumPopup(guiContent, (Enum)obj);
                if (isReadOnly == false && !newValue.Equals(obj))
                {
                    RegisterUndo();
                    obj = newValue;
                }
            }
        }
        else if (type == typeof(Color) || type == typeof(Color32))
        {
            if (shouldDisplay == true)
            {
                Color newValue = EditorGUILayout.ColorField(guiContent, (Color)obj);
                if (isReadOnly == false && !newValue.Equals(obj))
                {
                    Debug.Log(newValue.ToString() + " " + obj);
                    RegisterUndo();
                    obj = newValue;
                }
            }
        }
        else if (type.IsSubclassOf(typeof(UnityEngine.Object)))
        {
            if (shouldDisplay == true)
            {
                UnityEngine.Object newValue = EditorGUILayout.ObjectField(guiContent, (UnityEngine.Object)obj, type, true);
                if (isReadOnly == false && newValue != obj)
                {
                    Debug.Log(string.Format("{2}: newValue-{0}, obj-{1}", (newValue == null), (obj == null), guiContent.text));

                    RegisterUndo();
                    obj = newValue;
                }
            }
        }


        else if (type.IsArray)
        {
            if (maxDepth > 0)
            {
                if (foldoutIndex >= foldoutInfo.Count)
                {
                    foldoutInfo.Add(false);
                    RegisterUndo();
                }
                if (shouldDisplay)
                {
                    if (shouldDisplay == true)
                    {
                        EditorGUI.indentLevel -= 1;
                        bool oldValue = foldoutInfo[foldoutIndex];
                        foldoutInfo[foldoutIndex] = EditorGUILayout.Foldout(foldoutInfo[foldoutIndex], guiContent);
                        if (oldValue != foldoutInfo[foldoutIndex])
                        {
                            RegisterUndo();
                        }
                        EditorGUI.indentLevel += 1;
                    }
                }
                bool shouldDisplayChilds = shouldDisplay & foldoutInfo[foldoutIndex];
                foldoutIndex += 1;
                System.Array array = (System.Array)obj;
                if (shouldDisplayChilds)
                {
                    EditorGUI.indentLevel += 1;
                    int length = EditorGUILayout.IntField("Size", array.Length);
                    if (length != array.Length)
                    {
                        RegisterUndo();
                        Array newArray = Array.CreateInstance(array.GetType().GetElementType(), length);
                        Array.Copy(array, 0, newArray, 0, Math.Min(length, array.Length));
                        if (length > array.Length)
                        {
                            for (int i = array.Length; i < length; i++)
                            {
                                if (newArray.GetType().GetElementType() == typeof(String))
                                {
                                    if (i > 0)
                                    {
                                        newArray.SetValue(newArray.GetValue(i - 1), i);
                                    }
                                    else
                                    {
                                        newArray.SetValue("", i);
                                    }
                                }
                                else
                                {
                                    newArray.SetValue(Activator.CreateInstance(newArray.GetType().GetElementType(), true), i);
                                }
                            }
                        }
                        array = newArray;
                        obj   = array;
                    }
                    EditorGUI.indentLevel -= 1;
                }

                for (int index = 0; index < array.Length; index++)
                {
                    object arrElement = array.GetValue(index);
                    ObjectGUI(ref arrElement, array.GetType().GetElementType(), GetGUIContentFormObject(arrElement, null, index), shouldDisplayChilds, isReadOnly, maxDepth - 1, foldoutInfo, ref foldoutIndex);
                    //ObjectGUIIter(ref arrElement, array.GetType().GetElementType(), GetGUIContent(arrElement, null, index), isReadOnly, maxDepth - 1, foldoutInfo, ref foldoutIndex, shouldDisplayChilds);
                    array.SetValue(arrElement, index);
                }
            }
        }
        else if (type.IsClass == true)
        {
            if (maxDepth > 0)
            {
                EditorGUI.indentLevel += 1;
                ObjectGUIIter(ref obj, type, guiContent, isReadOnly, maxDepth - 1, foldoutInfo, ref foldoutIndex, shouldDisplay);
                EditorGUI.indentLevel -= 1;
            }
        }
    }
コード例 #58
0
        public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
        {
            if (sourceArray == null)
            {
                throw new ArgumentNullException("sourceArray");
            }

            if (destinationArray == null)
            {
                throw new ArgumentNullException("destinationArray");
            }

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length", Locale.GetText(
                                                          "Value has to be >= 0."));
            }
            ;

            if (sourceArray.Rank != destinationArray.Rank)
            {
                throw new RankException(SR.Rank_MultiDimNotSupported);
            }

            if (sourceIndex < 0)
            {
                throw new ArgumentOutOfRangeException("sourceIndex", Locale.GetText(
                                                          "Value has to be >= 0."));
            }
            ;

            if (destinationIndex < 0)
            {
                throw new ArgumentOutOfRangeException("destinationIndex", Locale.GetText(
                                                          "Value has to be >= 0."));
            }
            ;

            if (FastCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length))
            {
                return;
            }

            int source_pos = sourceIndex - sourceArray.GetLowerBound(0);
            int dest_pos   = destinationIndex - destinationArray.GetLowerBound(0);

            if (dest_pos < 0)
            {
                throw new ArgumentOutOfRangeException("destinationIndex", "Index was less than the array's lower bound in the first dimension.");
            }

            // re-ordered to avoid possible integer overflow
            if (source_pos > sourceArray.Length - length)
            {
                throw new ArgumentException("length");
            }

            if (dest_pos > destinationArray.Length - length)
            {
                string msg = "Destination array was not long enough. Check " +
                             "destIndex and length, and the array's lower bounds";
                throw new ArgumentException(msg, string.Empty);
            }

            Type src_type = sourceArray.GetType().GetElementType();
            Type dst_type = destinationArray.GetType().GetElementType();

            if (!Object.ReferenceEquals(sourceArray, destinationArray) || source_pos > dest_pos)
            {
                for (int i = 0; i < length; i++)
                {
                    Object srcval = sourceArray.GetValueImpl(source_pos + i);

                    try {
                        destinationArray.SetValueImpl(srcval, dest_pos + i);
                    } catch (ArgumentException) {
                        throw CreateArrayTypeMismatchException();
                    } catch {
                        if (CanAssignArrayElement(src_type, dst_type))
                        {
                            throw;
                        }

                        throw CreateArrayTypeMismatchException();
                    }
                }
            }
            else
            {
                for (int i = length - 1; i >= 0; i--)
                {
                    Object srcval = sourceArray.GetValueImpl(source_pos + i);

                    try {
                        destinationArray.SetValueImpl(srcval, dest_pos + i);
                    } catch (ArgumentException) {
                        throw CreateArrayTypeMismatchException();
                    } catch {
                        if (CanAssignArrayElement(src_type, dst_type))
                        {
                            throw;
                        }

                        throw CreateArrayTypeMismatchException();
                    }
                }
            }
        }
コード例 #59
0
        [System.Security.SecuritySafeCritical] // due to Marshal.SizeOf
        public void SetData(System.Array data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (!UnsafeUtility.IsArrayBlittable(data))
            {
                throw new ArgumentException(
                          string.Format("Array passed to GraphicsBuffer.SetData(array) must be blittable.\n{0}",
                                        UnsafeUtility.GetReasonForArrayNonBlittable(data)));
            }

            if (managedBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Length)
            {
                throw new ArgumentOutOfRangeException(String.Format("Bad indices/count arguments (managedBufferStartIndex:{0} graphicsBufferStartIndex:{1} count:{2})", managedBufferStartIndex, graphicsBufferStartIndex, count));
            }

            InternalSetData(data, managedBufferStartIndex, graphicsBufferStartIndex, count, Marshal.SizeOf(data.GetType().GetElementType()));
        }
コード例 #60
0
        public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
        {
            if (sourceArray == null)
            {
                throw new ArgumentNullException(nameof(sourceArray));
            }

            if (destinationArray == null)
            {
                throw new ArgumentNullException(nameof(destinationArray));
            }

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), "Value has to be >= 0.");
            }

            if (sourceArray.Rank != destinationArray.Rank)
            {
                throw new RankException(SR.Rank_MultiDimNotSupported);
            }

            if (sourceIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(sourceIndex), "Value has to be >= 0.");
            }

            if (destinationIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(destinationIndex), "Value has to be >= 0.");
            }

            if (FastCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length))
            {
                return;
            }

            int source_pos = sourceIndex - sourceArray.GetLowerBound(0);
            int dest_pos   = destinationIndex - destinationArray.GetLowerBound(0);

            if (dest_pos < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(destinationIndex), "Index was less than the array's lower bound in the first dimension.");
            }

            // re-ordered to avoid possible integer overflow
            if (source_pos > sourceArray.Length - length)
            {
                throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
            }

            if (dest_pos > destinationArray.Length - length)
            {
                throw new ArgumentException("Destination array was not long enough. Check destIndex and length, and the array's lower bounds", nameof(destinationArray));
            }

            Type src_type    = sourceArray.GetType().GetElementType();
            Type dst_type    = destinationArray.GetType().GetElementType();
            var  dst_type_vt = dst_type.IsValueType;

            // Need to check types even if nothing is copied
            if (length == 0)
            {
                var src_etype = RuntimeTypeHandle.GetCorElementType((RuntimeType)src_type);
                var dst_etype = RuntimeTypeHandle.GetCorElementType((RuntimeType)dst_type);

                // FIXME: More checks
                bool match = true;
                switch (dst_etype)
                {
                case CorElementType.ELEMENT_TYPE_OBJECT:
                case CorElementType.ELEMENT_TYPE_STRING:
                case CorElementType.ELEMENT_TYPE_CLASS:
                case CorElementType.ELEMENT_TYPE_ARRAY:
                case CorElementType.ELEMENT_TYPE_SZARRAY:
                    if (src_type.IsPointer)
                    {
                        match = false;
                    }
                    break;

                case CorElementType.ELEMENT_TYPE_PTR:
                    switch (src_etype)
                    {
                    case CorElementType.ELEMENT_TYPE_OBJECT:
                    case CorElementType.ELEMENT_TYPE_STRING:
                    case CorElementType.ELEMENT_TYPE_CLASS:
                    case CorElementType.ELEMENT_TYPE_ARRAY:
                    case CorElementType.ELEMENT_TYPE_SZARRAY:
                        match = false;
                        break;

                    default:
                        break;
                    }
                    break;

                default:
                    break;
                }
                if (!match)
                {
                    throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
                }
            }

            if (!Object.ReferenceEquals(sourceArray, destinationArray) || source_pos > dest_pos)
            {
                for (int i = 0; i < length; i++)
                {
                    Object srcval = sourceArray.GetValueImpl(source_pos + i);

                    if (srcval == null && dst_type_vt)
                    {
                        throw new InvalidCastException();
                    }

                    try {
                        destinationArray.SetValueImpl(srcval, dest_pos + i);
                    } catch (ArgumentException) {
                        throw CreateArrayTypeMismatchException();
                    } catch (InvalidCastException) {
                        if (CanAssignArrayElement(src_type, dst_type))
                        {
                            throw;
                        }
                        throw CreateArrayTypeMismatchException();
                    }
                }
            }
            else
            {
                for (int i = length - 1; i >= 0; i--)
                {
                    Object srcval = sourceArray.GetValueImpl(source_pos + i);

                    try {
                        destinationArray.SetValueImpl(srcval, dest_pos + i);
                    } catch (ArgumentException) {
                        throw CreateArrayTypeMismatchException();
                    } catch {
                        if (CanAssignArrayElement(src_type, dst_type))
                        {
                            throw;
                        }

                        throw CreateArrayTypeMismatchException();
                    }
                }
            }
        }