search
HomeBackend DevelopmentC#.Net TutorialArray parsing with non-zero lower bound in C#

When talking about arrays, when asked what number the array starts from, it is estimated that most programmers will directly say that the array certainly starts from 0. This answer is of course correct. Now let’s take a look at arrays with a non-zero lower limit in C#.

First, let’s take a look at the relevant introduction to arrays:

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

2. Classification of arrays: In CLR, arrays can be divided into one-dimensional arrays, multi-dimensional arrays, and interleaved arrays.

3. Type of array: Since all arrays inherit from the abstract type System.Array, and this type inherits from System.Object, this means that arrays are reference types.

When creating an array, in addition to the array elements, the memory block occupied by the array object also contains a type object pointer, a synchronized index block and an additional member. The above classification of arrays mentioned "interleaved arrays". Since the CLR supports interleaved arrays, interleaved arrays can be implemented in C#. An interleaved array is an array composed of arrays. Accessing the elements of an interleaved array means that it must be done twice. Or multiple array accesses.

In the process of performing related operations on the array, when the array is passed to a method as an actual parameter, what is actually passed is a reference to the array, so the called method can modify the elements in the array. (If you do not want to be modified, you must generate a copy of the array and pass this copy to the method.)

Here is a method to convert an array into a DataTable:

       /// <summary>
        /// 整数型二维数组转换成DataTable
        /// </summary>
        /// <param name="intDyadicArray"></param>
        /// <param name="messageOut"></param>
        /// <param name="dataTableColumnsName"></param>
        /// <returns></returns>
        public DataTable DyadicArrayToDataTable(int[,] intDyadicArray, out string messageOut,
            params object[] dataTableColumnsName)
        {
            var returnDataTable = new DataTable();
            //验证列与所传入的字符是否相符
            if (dataTableColumnsName.Length != intDyadicArray.GetLength(1))
            {
                messageOut = "DataTable列数与二维数组列数不符,请调整列数";
                return returnDataTable;
            }
            //添加列
            for (var dataTableColumnsCount = 0;
                dataTableColumnsCount < dataTableColumnsName.Length;
                dataTableColumnsCount++)
            {
                returnDataTable.Columns.Add(dataTableColumnsName[dataTableColumnsCount].ToString());
            }
            //添加行
            for (var dyadicArrayRow = 0; dyadicArrayRow < intDyadicArray.GetLength(0); dyadicArrayRow++)
            {
                var addDataRow = returnDataTable.NewRow();
                for (var dyadicArrayColumns = 0;
                    dyadicArrayColumns < intDyadicArray.GetLength(1);
                    dyadicArrayColumns++)
                {
                    addDataRow[dataTableColumnsName[dyadicArrayColumns].ToString()] =
                        intDyadicArray[dyadicArrayRow, dyadicArrayColumns];
                }
                returnDataTable.Rows.Add(addDataRow);
            }
            //返回提示与DataTable
            messageOut = "DataTable成功转换";
            return returnDataTable;
        }

The above is the operation method for converting an integer array into a DataTable , as for the conversion of other types, such as bytes, floating point and other types, just modify the relevant parameters, and you can also modify the parameter types accordingly, which will not be introduced in detail here.

Next we will learn more about the "lower limit non-zero array" in detail:

Since the lower limit non-zero array has not been better optimized in terms of performance, it will be less common in general use. If you don't care about performance If there is a loss or need for cross-language portability, consider using a non-zero array. The concept of "lower bound non-zero array" will not be introduced, as its name suggests.

​ Use Array’s CreateInstance() method to create in C#. This method has several overloads, 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 calling CreateInstance(), allocate memory for the array, save the parameter information to the overhead portion of the array's memory, and then 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); 
        }

After seeing the above code, you should have a general understanding of the creation of non-zero base arrays. Next, let’s take a detailed look at the underlying code of the Ensures() method:

public static void Ensures(bool condition)
        {
            AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); 
        }
[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&#39;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 of creating a non-zero base array will not be introduced in depth. If you need to use it, you can select the corresponding version implementation based on the provided method overload.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.