Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

Section 20.10: Array covariance

string[] strings = new[] {"foo", "bar"};

object[] objects = strings; // implicit conversion from string[] to object[]

This conversion is not type-safe. The following code will raise a runtime exception:

string[] strings = new[] {"Foo"}; object[] objects = strings;

objects[0] = new object(); // runtime exception, object is not string

string str = strings[0]; // would have been bad if above assignment had succeeded

Section 20.11: Arrays as IEnumerable<> instances

All arrays implement the non-generic IList interface (and hence non-generic ICollection and IEnumerable base interfaces).

More importantly, one-dimensional arrays implement the IList<> and IReadOnlyList<> generic interfaces (and their base interfaces) for the type of data that they contain. This means that they can be treated as generic enumerable types and passed in to a variety of methods without needing to first convert them to a non-array form.

int[] arr1 = { 3, 5, 7 };

IEnumerable<int> enumerableIntegers = arr1; //Allowed because arrays implement IEnumerable<T>

List<int> listOfIntegers = new List<int>();

listOfIntegers.AddRange(arr1); //You can pass in a reference to an array to populate a List.

After running this code, the list listOfIntegers will contain a List<int> containing the values 3, 5, and 7.

The IEnumerable<> support means arrays can be queried with LINQ, for example arr1.Select(i => 10 * i).

Section 20.12: Checking if one array contains another array

public static class ArrayHelpers

{

public static bool Contains<T>(this T[] array, T[] candidate)

{

if (IsEmptyLocate(array, candidate)) return false;

if (candidate.Length > array.Length) return false;

for (int a = 0; a <= array.Length - candidate.Length; a++)

{

if (array[a].Equals(candidate[0]))

{

int i = 0;

for (; i < candidate.Length; i++)

{

if (false == array[a + i].Equals(candidate[i])) break;

}

if (i == candidate.Length) return true;

}

}

GoalKicker.com – C# Notes for Professionals

94

return false;

}

static bool IsEmptyLocate<T>(T[] array, T[] candidate)

{

return array == null

||candidate == null

||array.Length == 0

||candidate.Length == 0

||candidate.Length > array.Length;

}

}

/// Sample

byte[] EndOfStream = Encoding.ASCII.GetBytes("---3141592---");

byte[] FakeReceivedFromStream = Encoding.ASCII.GetBytes("Hello, world!!!---3141592---"); if (FakeReceivedFromStream.Contains(EndOfStream))

{

Console.WriteLine("Message received");

}

GoalKicker.com – C# Notes for Professionals

95