Студопедия

Главная страница Случайная страница

Разделы сайта

АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника






Not required to assign the generic type with the method call. The generic method can be invoked as simply






as non-generic methods:

int i = 4;

int j = 5;

Swap(ref i, ref j);

Desc: To show the features of generic methods, assume the following Account class that contains Name and Balance properties.All the accounts where the balance should be accumulated are added to an accounts list of type

List< Account>:

var accounts = new List< Account> ()

{new Account(" Christian", 1500),

new Account(" Stephanie", 2200),

new Account(" Angela", 1800)};

to accumulate all Account objects is by looping through all Account objects with a foreach statement, as shown here. Because the foreach statement uses the IEnumerable interface to iterate the elements of a collection.The foreach statement works with every object implementing IEnumerable. This way, the AccumulateSimple() method can be used with all collection classes that implement the interface IEnumerable< Account>. In the implementation of this method, the property Balance of the Account

object is directly accessed:

Public static class Algorithm

{

public static decimal AccumulateSimple(IEnumerable< Account> source)

{

decimal sum = 0;

Foreach (Account a in source)

{

sum += a.Balance;

}

Return sum;

}

}

The AccumulateSimple() method is invoked this way:

decimal amount = Algorithm.AccumulateSimple(accounts);

39. Arrays in C#.

Def: An array is a data structure that contains a number of elements of the same type.

Desc: An array is declared by defining the type of elements inside the array followed by empty brackets and a variable name. For example, int[] myArray;

After declaring an array, memory must be allocated to hold all the elements of the array. An array is a reference type, so memory on the heap must be allocated. You do this by initializing the variable of the array using the new operator with the type and the number of elements inside the array. Here you specify the size of the array:

myArray = new int[4];

The array cannot be resized after the size was specifi ed without copying all elements.

To declare and initialize an array, you can use a single line:

int[] myArray = new int[4]; or int[] myArray = new int[] {4, 7, 11, 2};

Using curly brackets you can write the array declaration and initialization shorter:

int[] myArray = {4, 7, 11, 2};

After an array is declared and initialized, you can access the array elements using an indexer. With the indexer, you pass the element number to access the array. The indexer starts with 0 and the highest number is the number of elements minus one. example,

int[] myArray = new int[] {4, 7, 11, 2};

int v1 = myArray[0]; // read first element

int v2 = myArray[1]; // read second element

myArray[3] = 44; // change fourth element






© 2023 :: MyLektsii.ru :: Мои Лекции
Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав.
Копирование текстов разрешено только с указанием индексируемой ссылки на источник.