logo search
CSharp_Prog_Guide

Неявно типизированные массивы в инициализаторах объектов12

При создании анонимного типа, содержащего массив, этот массив неявно типизируется в инициализаторе объекта типа. В следующем примере contacts является неявно типизированным массивом анонимных типов, каждый из которых содержит массив с именем PhoneNumbers. Обратите внимание на то, что ключевое слово var внутри инициализаторов объектов не используется.

var contacts = new[]

{

new {

Name = " Eugene Zabokritski",

PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }

},

new {

Name = " Hanying Feng",

PhoneNumbers = new[] { "650-555-0199" }

}

};

Strings

The following sections discuss the string data type, which is an alias for the String class.

Using Strings

A C# string is an array of characters that is declared by using the string keyword. A string literal is declared by using quotation marks, as shown in the following example:

string s = "Hello, World!";

You can extract substrings, and concatenate strings as in the following example:

string s1 = "orange";

string s2 = "red";

s1 += s2;

System.Console.WriteLine(s1); // outputs "orangered"

s1 = s1.Substring(2, 5);

System.Console.WriteLine(s1); // outputs "anger"

String objects are immutable: they cannot be changed after they have been created. Methods that act on strings actually return new string objects. In the previous example, when the contents of s1 and s2 are concatenated to form a single string, the two strings that contain "orange" and "red" are both unmodified. The += operator creates a new string that contains the combined contents. The result is that s1 now refers to a different string completely. A string that contains just "orange" still exists, but is no longer referenced when s1 is concatenated.

Note:

Use caution when you create references to strings. If you create a reference to a string, and then "modify" the string, the reference will continue to point to the original object, not the new object that was created when the string was modified. The following code illustrates the danger:

string s1 = "Hello";

string s2 = s1;

s1 += " and goodbye.";

Console.WriteLine(s2); //outputs "Hello"

Строки

В следующих разделах рассматривается тип данных string, являющийся псевдонимом класса String.