Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

string firstName = "Wei-Meng";

string lastName = "Lee";

Console.WriteLine("Hello, {0}", firstName);

Console.WriteLine("Hello, {0} {1}", firstName, lastName);

Observe that the last two statements contain different numbers of parameters. In fact, the WriteLine()method is overloaded, and one of the overloaded methods has a parameter of type params(see Figure 13-3). The paramskeyword lets you specify a method parameter that takes an argument where the number of arguments is variable.

Figure 133 A result of declaring the parameter type to be of params is that - фото 188

Figure 13-3

A result of declaring the parameter type to be of params is that callers to the method do not need to explicitly create an array to pass into the method. Instead, they can simply pass in a variable number of parameters.

To use the paramstype in your own function, you define a parameter with the paramskeyword:

private void PrintMessage(string prefix, params string[] msg) {

}

To extract the parameter array passed in by the caller, treat the params parameter like a normal array, like this:

private void PrintMessage(string prefix, params string[] msg) {

foreach (string s in msg)

Console.WriteLine("{0}>{1}", prefix, s);

}

When calling the PrintMessage()function, you can pass in a variable number of parameters:

PrintMessage("C# Part 1", "Arrays", "Index", "Collections");

PrintMessage("C# Part 2", "Objects", "Classes");

These statements generate the following output:

C# Part 1>Arrays

C# Part 1>Index

C# Part 1>Collections

C# Part 2>Objects

C# Part 2>Classes

A paramsparameter must always be the last parameter defined in a method declaration.

Copying Arrays

To copy from one array to another, use the Copy()method from the Arrayabstract base class:

int[] num = new int[5] { 1, 2, 3, 4, 5 };

int[] num1 = new int[5];

num.CopyTo(num1, 0);

These statements copy all the elements from the numarray into the num1array. The second parameter in the CopyTo()method specifies the index in the array at which the copying begins.

Collections Interfaces

The System.Collectionsnamespace contains several interfaces that define basic collection functionalities:

The interfaces described in the following list are the generic versions of the respective interfaces. Beginning with C# 2.0, you should always try to use the generic versions of the interfaces for type safety. Chapter 9 discusses the use of generics in the C# language.

Interface Description
IEnumerableand IEnumerator Enable you to loop through the elements in a collection.
ICollection Contains items in a collection and provides the functionality to copy elements to an array. Inherits from IEnumerable.
IComparerand IComparable Enable you to compare objects in a collection.
IList Inherits from ICollectionand provides functionality to allow members to be accessed by index.
IDictionary Similar to IList, but members are accessed by key value rather than index.

The ICollectioninterface is the base interface for classes in the System.Collectionsnamespace.

Dynamic Arrays Using the ArrayList Class

Arrays in C# have a fixed size once they are initialized. For example, the following defines a fixed- size array of five integer elements:

int[] num = new int[5];

If you need to dynamically increase the size of an array during runtime, use the ArrayListclass instead. You use it like an array, but its size can be increased dynamically as required.

The ArrayListclass is located within the System.Collectionsnamespace, so you need to import that System.Collectionsnamespace before you use it. The ArrayListclass implements the IListinterface.

To use the ArrayListclass, you first create an instance of it:

ArrayList arrayList = new ArrayList();

Use the Add()method to add elements to an ArrayListobject:

arrayList.Add("Hello");

arrayList.Add(25);

arrayList.Add(new Point(3,4));

arrayList.Add(3.14F);

Notice that you can add elements of different types to an ArrayListobject.

To access an element contained within an ArrayListobject, specify the element's index like this:

Console.WriteLine(arrayList[0]); //---Hello---

Console.WriteLine(arrayList[1]); //---25---

Console.WriteLine(arrayList[2]); //---{X=3,Y=4}

Console.WriteLine(arrayList[3]); //---3.14---

The ArrayListobject can contain elements of different types, so when retrieving items from an ArrayListobject make sure that the elements are assigned to variables of the correct type. Elements retrieved from an ArrayListobject belong to Objecttype.

You can insert elements to an ArrayListobject using the Insert()method:

arrayList.Insert(1, " World!");

After the insertion, the ArrayListobject now has five elements:

Console.WriteLine(arrayList[0]); //---Hello---

Console.WriteLine(arrayList[1]); //---World!---

Console.WriteLine(arrayList[2]); //---25---

Console.WriteLine(arrayList[3]); //---{X=3,Y=4}---

Console.WriteLine(arrayList[4]); //---3.14---

To remove elements from an ArrayListobject, use the Remove()or RemoveAt()methods:

arrayList.Remove("Hello");

arrayList.Remove("Hi"); //---cannot find item---

arrayList.Remove(new Point(3, 4));

arrayList.RemoveAt(1);

After these statements run, the ArrayListobject has only two elements:

Console.WriteLine(arrayList[0]); //---World!---

Console.WriteLine(arrayList[1]); //---3.14---

If you try to remove an element that is nonexistent, no exception is raised (which is not very useful). It would be good to use the Contains()method to check whether the element exists before attempting to remove it:

if (arrayList.Contains("Hi")) arrayList.Remove("Hi");

else Console.WriteLine("Element not found.");

You can also assign the elements in an ArrayListobject to an array using the ToArray()method:

object[] objArray;

objArray = arrayList.ToArray();

foreach (object o in objArray)

Console.WriteLine(o.ToString());

Because the elements in the ArrayListcan be of different types you must be careful handling them or you run the risk of runtime exceptions. To work with data of the same type, it is more efficient to use the generic equivalent of the ArrayListclass — the Listclass, which is type safe. To use the Listclass, you simply instantiate it with the type you want to use and then use the different methods available just like in the ArrayListclass:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x