C # array parsing with a non-zero lower limit,

Source: Internet
Author: User

C # array parsing with a non-zero lower limit,

When talking about arrays, when asked about the number of arrays starting from, it is estimated that most programmers will directly say that arrays start from 0. Of course there is no error in this answer. Now let's take a look at the array whose lower limit is not 0 in C.

First, let's take a look at the introduction of Arrays:

1. array: An array is a mechanism that allows multiple data items to be processed as a set.

2. array classification: In CLR, Arrays can be divided into one-dimensional arrays, multi-dimensional arrays, and staggered arrays.

3. Array type: because all arrays are inherited from the abstract type System. Array, And this type is inherited from System. Object, this indicates that the Array is a reference type.

When creating an array, in addition to array elements, the memory block occupied by the array object also contains a type object pointer, a Synchronous Index block, and an additional member. The preceding section mentions "staggered arrays" in array classification. CLR supports staggered arrays, so in C #, You can implement staggered arrays, which are arrays composed of arrays, elements accessing the staggered array mean that two or more group accesses are required.

When an array is passed as a real parameter to a method during related operations on the array, the reference to the array is actually passed, so the called method can modify the elements in the array. (If you do not want to modify it, you must generate a copy of the array and pass the copy to the method .)

The following describes how to convert an array to a able:

/// <Summary> /// converts an integer two-dimensional array to a DataTable // </summary> /// <param name = "intDyadicArray"> </param> // /<param name = "messageOut"> </param> // <param name = "ableablecolumnsname"> </param> // <returns> </returns> public DataTable dyadicArrayToDataTable (int [,] intDyadicArray, out string messageOut, params object [] ableablecolumnsname) {var returnDataTable = new DataTable (); // verify whether the column matches the passed characters if (dataTableC OlumnsName. Length! = IntDyadicArray. getLength (1) {messageOut = "the number of DataTable columns does not match the number of two-dimensional array columns. Please adjust the number of columns"; return returnDataTable;} // Add the column for (var dataTableColumnsCount = 0; dataTableColumnsCount <ableablecolumnsname. length; dataTableColumnsCount ++) {returnDataTable. columns. add (dataTableColumnsName [dataTableColumnsCount]. toString ();} // Add a row for (var dyadicArrayRow = 0; dyadicArrayRow <intDyadicArray. getLength (0); dyadicArrayRow ++) {var addDataRow = returnDataTable. newRow (); for (var dyadicArrayColumns = 0; dyadicArrayColumns <intDyadicArray. getLength (1); dyadicArrayColumns ++) {addDataRow [ableablecolumnsname [dyadicArrayColumns]. toString ()] = intDyadicArray [dyadicArrayRow, dyadicArrayColumns];} returnDataTable. rows. add (addDataRow);} // The returned message is "DataTable messageOut =" DataTable successfully converted "; return returnDataTable ;}

The preceding operation is to convert an integer array to a able. for conversion of other types, such as byte and floating point types, modify the relevant parameters. You can also modify the parameter types, I will not go into detail here.

Next, let's take a look at the "minimum non-zero array" knowledge:

The lower-limit non-zero array is not optimized in terms of performance, so it is rarely used. If you do not care about performance loss or need to port the array across languages, you can consider using a non-zero array. The concept of "minimum non-zero array" is not introduced, as shown in its name.

The CreateInstance () method of Array is used in C # To create an object. This method has several overload operations, allowing you to specify the Array element type, Array dimension, the lower limit of each dimension, and the number of elements in each dimension.

When CreateInstance () is called, allocate memory for the array, save the parameter information to the overhead of the array memory, and return a reference to the array.

Next, let's take a look at the underlying implementation code of this method:

 [System.Security.SecuritySafeCritical]  // auto-generated         public unsafe static Array CreateInstance(Type elementType, int length)        {             if ((object)elementType == null)                throw new ArgumentNullException("elementType");            if (length < 0)                throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));             Contract.Ensures(Contract.Result<Array>() != null);            Contract.Ensures(Contract.Result<Array>().Length == length);             Contract.Ensures(Contract.Result<Array>().Rank == 1);             Contract.EndContractBlock();             RuntimeType t = elementType.UnderlyingSystemType as RuntimeType;            if (t == null)                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"elementType");            return InternalCreate((void*)t.TypeHandle.Value,1,&length,null);         }

If you see the above Code, you should have a general understanding of creating a non-zero base array. Next, let's take a look at the underlying code of the Ensures () method:

public static void Ensures(bool condition)        {            AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures");         }
static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind); 
        [SecuritySafeCritical]        static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind)         {            if (_assertingMustUseRewriter)                 System.Diagnostics.Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?");             _assertingMustUseRewriter = true;            Assembly thisAssembly = typeof(Contract).Assembly;              StackTrace stack = new StackTrace();             Assembly probablyNotRewritten = null;            for (int i = 0; i < stack.FrameCount; i++)             {                 Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly;                if (caller != thisAssembly)                 {                    probablyNotRewritten = caller;                    break;                }             }             if (probablyNotRewritten == null)                 probablyNotRewritten = thisAssembly;            String simpleName = probablyNotRewritten.GetName().Name;             System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, Environment.GetResourceString("MustUseCCRewrite", contractKind, simpleName), null, null, null);            _assertingMustUseRewriter = false;        } 

The method for creating a non-zero base array is not described in detail. If you need to use it, you can select the corresponding version implementation based on the method overload.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.