Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use arrays in C #

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about how to use the array in C#. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article, let's take a look at it.

If you need to use multiple objects of the same type, you can use arrays and collections (described later). C # declares, initializes, and uses arrays with special tokens. The Array class works in the background, providing several methods for sorting and filtering elements in an array. Using the enumerator, you can iterate over all the elements in the array.

If you need to use multiple objects of different types, you can use the Tuple (tuple) type.

one。 Simple array (one-dimensional array)

An array is a data structure that can contain multiple elements of the same type.

1. Declaration of the array

When declaring an array, you define the element type in the array, followed by a pair of empty square brackets and a variable name.

Int [] myArray;2. Initialization of array

After the array is declared, memory must be allocated for the array to hold all the elements of the array. The array is a reference type, so it must be allocated memory on the heap. To do this, you should use the new operator to initialize the array's variables by specifying the type and number of elements in the array.

MyArray = new int [4]

After the array is declared and initialized, the variable myArray references four integer values, which are on the managed heap:

After you specify the size of the array, you cannot resize the array. If you don't know in advance how many elements an array should contain, you can use collections.

In addition to declaring and initializing arrays in two statements, you can declare and initialize arrays in one statement:

Int [] myArray = new int [4]

You can also use an array initializer to copy for each element of the array. Array initializers can only be used when declaring array variables, not after declaring arrays.

Int [] myArray = new int [4] {1pm 3pm 5pm 7}

If you initialize an array with curly braces, you can not specify the size of the array because the compiler automatically counts the number of elements:

Int [] myArray = new int [] {1pm 3pm 5pm 7}

You can also use a simpler form:

Int [] myArray = {1, 3, 5, 5, 7}; 3. Access array elements

After the array is declared and initialized, you can use the indexer to access its elements. Arrays only support indexers with integer parameters.

The indexer always starts with 0, which represents the first element. The maximum value that can be passed to the indexer is the number of elements minus 1, because the index starts at 0:

Int [] myArray = {1 myArray 3 myArray 5 7}; int v1 = myArray [0]; int v2 = myArray [1]; myArray [3] = 4

You can use the Length attribute of an array to get the number of elements.

4. Use reference types in arrays

Arrays can declare arrays of custom types as well as arrays of predefined types.

Public class Person {public string FirstName {get; set;} public string LastName {get; set;} public override string ToString () {return String.Format ("{0} {1}", FirstName, LastName);} Person [] myPersons = new Person [2]; myPersons [0] = new Person {FirstName = "Ayrton", LastName = "Senna"} MyPersons [1] = new Person {FirstName = "Michael", LastName = "Schumacher"}

If the elements in the array are reference types, memory must be allocated for each array element. If an unallocated memory element in the array is used, an exception of type NullReferenceException is thrown.

The following is the memory situation:

You can also use array initializers for custom types:

Person [] myPersons2 = {new Person {FirstName= "Ayrton", LastName= "Senna"}, new Person {FirstName= "Michael", LastName= "Schumacher"}} Multidimensional array

A multidimensional array is indexed by two or more integers.

To declare a multidimensional array in C #, you need to put a comma in square brackets. The array should specify the size of each dimension (also known as the order) when initializing.

Int [,] twoDim = new int [3Legree 3]; twoDim [0meme0] = 1twittwoDim [0meme1] = 2twittwoDim [0memo 2] = 3mittwoDim [1memo 0] = 4mitttwoDim [1recorder 1] = 5twoDim [1recorder 2] = 6tertwoDim [2hel0] = 7twittwoDim [2jue 1] = 8twittwoDim [2Yue2] = 9

After you declare an array, you cannot change its order.

You can also use initializers to initialize multidimensional arrays:

Int [,] twoDim = {{1rem 2je 3}, {4je 5je 6}, {7pm 8je 9}}

When using an array initializer, each element of the array must be initialized, and no element must be left out.

Declare a three-digit array:

Int [,] threeDim = {1 rect 2}, {3jue 4}}, {{5 rect 6}, {7 jue 8}}, {{9 recorder 10}, {11je 12}; Console.WriteLine (threeDim [0jue 1]); III. Sawtooth array

The size of the two-dimensional array corresponds to a rectangle, while the size setting of the sawtooth array is more flexible, and each row can have a different size in the sawtooth array.

When declaring a jagged array, place the left and right parentheses in turn. When initializing an aliased array, only the number of rows contained in the array is set in the first square bracket. The second square bracket that defines the number of elements in each row is set to empty because each row of this type of array contains a different number of elements. After that, specify the number of elements in each row:

Int [] [] jagged = new int [3] []; jagged [0] = new int [2] {1score2}; jagged [1] = new int [4] {3pcre 4je 5je 6}; jagged [2] = new int [3] {7je 8}

The code that iterates over all the elements in the jagged array can be placed in a nested for loop. Iterate over each line in the outer for loop and each element in the line in the inner for loop:

For (int row= 0 index; row = 0; iMury -) {yield return names [I];}} public IEnumerable Subset (int index, int length) {for (int I = index; I)

< index + length;i++)        {          yield return names[i];        }      }    } 客户端代码:     var titles = new MusicTitles();    foreach (var title in titles)    {      Console.WriteLine(title);    }    Console.WriteLine();    Console.WriteLine("reverse");    foreach (var title in titles.Reverse())    {      Console.WriteLine(title);    }    Console.WriteLine();    Console.WriteLine("subset");    foreach (var title in titles.Subset(2, 2))    {      Console.WriteLine(title);    }(2).用yield return 返回枚举器public class GameMoves { private IEnumerator cross; private IEnumerator circle; public GameMoves() { cross = Cross(); circle = Circle(); } private int move = 0; const int MaxMoves = 9; public IEnumerator Cross() { while (true) { Console.WriteLine("Cross, move {0}", move); if (++move >

= MaxMoves) yield break; yield return circle;}} public IEnumerator Circle () {while (true) {Console.WriteLine ("Circle, move {0}", move); if (+ + move > = MaxMoves) yield break; yield return cross;}}

Client code:

Var game = new GameMoves (); IEnumerator enumerator = game.Cross (); while (enumerator.MoveNext ()) {enumerator = enumerator.Current as IEnumerator;}

This alternately calls the Cross () and Circle () methods.

seven。 Tuple (Tuple)

Tuples can merge different types of objects. Tuples originate from functional programming languages such as F#. In .NET Framework, tuples are available for all .net languages.

The .NET Framework defines eight generic Tuple classes and a static Tuple class that act as factories for tuples. Different generic Tuple classes support a different number of elements. For example, Tuple contains one element and Tuple contains two elements.

Tuple name = new Tuple ("Jochen", "Rindt")

Tuples can also be created using the static Create () method of the static Tuple class. The generic parameter of the Create () method determines the type of tuple to instantiate:

Public static Tuple Divide (int dividend, int divisor) {int result = dividend / divisor; int reminder = dividend% divisor; return Tuple.Create (result, reminder);}

You can access the items of a tuple with the properties Item1 and Item2:

Var result = Divide (5,2); Console.WriteLine ("result of division: {0}, reminder: {1}", result.Item1, result.Item2)

If the tuple contains more than eight items, you can use the Tuple class definition with eight parameters. The last template parameter is TRest, which means that a tuple must be passed to it. In this way, you can create a tuple with any parameter.

Var tuple = Tuple.Create ("Stephanie", "Alina", "Nagel", 2009, 6, 2, 1.37, Tuple.Create (52, 3490)) Structure comparison

Both arrays and tuples implement interfaces IStructuralEquatable and IStructuralComparable. These two interfaces can compare not only references, but also content. These interfaces are explicitly implemented, so arrays and tuples need to be cast to this interface when used.

API IStructuralEquatable is used to compare whether two tuples or arrays have the same internal identity, and API IStructuralComparable is used to sort tuples or arrays.

Example of IStructuralEquatable interface:

Write a Person class that implements the IEquatable interface, which defines a strongly typed Equals () method that compares the values of FirstName and LastName:

Public class Person: IEquatable {public int Id {get; private set;} public string FirstName {get; set;} public string LastName {get; set;} public override string ToString () {return String.Format ("{0}, {1} {2}", Id, FirstName, LastName);} public override bool Equals (object obj) {if (obj = = null) return base.Equals (obj) Return Equals (obj as Person);} public override int GetHashCode () {return Id.GetHashCode ();} # region IEquatable Members public bool Equals (Person other) {if (other = = null) return base.Equals (other); return this.FirstName = = other.FirstName & & this.LastName = = other.LastName;} # endregion}

Create two arrays of type Person that contain the same content:

Var janet = new Person {FirstName = "Janet", LastName = "Jackson"}; Person [] persons1 = {new Person {FirstName = "Michael", LastName = "Jackson"}, janet}; Person [] persons2 = {new Person {FirstName = "Michael", LastName = "Jackson"}, janet}

Because two variables refer to two different arrays,! = returns True:

If (persons1! = persons2) Console.WriteLine ("not the same reference")

For the Equals method defined by the IStructuralEquatable interface, the first parameter is the object type and the second parameter is the IEqualityComparer type. When you call this method, you can define how to compare by passing an object that implements EqualityComparer. A default implementation of IEqualityComparer is done through the EqualityComparer class. This implementation checks whether the T type implements the IEquatable interface and calls the IEquatable.Equals () method. If the class does not implement the IEquatable interface, call the Equals () method in the Object base class:

If ((persons1 as IStructuralEquatable) .equals (persons2, EqualityComparer.Default)) {Console.WriteLine ("the same content");}

Tuple example:

The Tuple class provides two Epuals () methods: one overrides the Epuals method in the Object base class and takes object as a parameter, the second is defined by the IStructuralEquatable interface, and takes object and IEqualityComparer as parameters.

Var T1 = Tuple.Create (1, "Stephanie"); var T2 = Tuple.Create (1, "Stephanie"); if (T1! = T2) Console.WriteLine ("not the same reference to the tuple")

This method uses EqualityComparer.Default to get an ObjectEqualityComparer for comparison. This calls the Object.Equals () method to compare each item of the tuple:

If (t1.Equals (T2)) Console.WriteLine ("equals returns true")

You can also use the TupleComparer class to create a custom IEqualityComparer

TupleComparer tc = new TupleComparer (); if ((T1 as IStructuralEquatable) .equals (T2, tc)) {Console.WriteLine ("yes, using TubpleComparer");} class TupleComparer: IEqualityComparer {# region IEqualityComparer Members public new bool Equals (object x, object y) {bool result = x.Equals (y); return result } public int GetHashCode (object obj) {return obj.GetHashCode ();} # endregion} above is all the content of the article "how to use arrays in C#". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

  • How to encapsulate vue Calendar components

    This article will explain in detail how to encapsulate the vue calendar component. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article. The code of the encapsulated component is shown below

    © 2024 shulou.com SLNews company. All rights reserved.

    12
    Report