Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ProgBasics_lec05-6_class_members

.pdf
Скачиваний:
10
Добавлен:
14.04.2015
Размер:
480.56 Кб
Скачать

Пример с ref

static void Swap(ref int x, ref int y)

{

int temp = x; x = y;

y = temp;

}

static void Main(string[] args)

{

int a = 2, b = -5; Swap(ref a, ref b);

Console.WriteLine("a = {0}, b = {1}", a, b);

}

-5, 2

Пример похитрее

static string s; static void F(ref string a, ref string b)

{

s = "One"; a = "Two"; b = "Three";

}

static void G()

{

F(ref s, ref s);

}

Пример из BCL

public static bool TryParse(string s, out int result)

{

return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo,

out result);

}

internal static unsafe bool TryParseInt32(string s, NumberStyles style, NumberFormatInfo info, out int result)

{

Number.NumberBuffer numberBuffer =

new Number.NumberBuffer(stackalloc byte[Number.NumberBuffer.NumberBufferBytes]);

result = 0;

if (!Number.TryStringToNumber(s, style, ref numberBuffer, info, false))

{

return false;

}

if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)

{

if (!Number.HexNumberToInt32(ref numberBuffer, ref result)) return false;

}

else if (!Number.NumberToInt32(ref numberBuffer, ref result))

{

return false;

}

return true;

}

usage

int value;

bool success = int.TryParse(Console.ReadLine(), out value);

ref или out?

Общее:

передают параметр по ссылке Разница:

ref не позволяет передать неинициализированную переменную в метод

Parameter arrays

static void Main(string[] args)

{

int[] arr = { 1, 2, 3 }; F(arr);

F(10, 20, 30, 40); F();

}

static void F(params int[] args)

{

Console.Write("Array contains {0} elements:", args.Length); Console.WriteLine(string.Join(" ", args));

}

Конструкторы

Конструктор – элемент класса, который реализует действия, требуемые для инициализации экземпляра класса.

Говоря проще – конструктор позволяет привести объект в некое начальное состояние.

Технически конструктор – обычный метод.

Конструкторы

[модификаторы]<имя>([параметры]) [ : this/base ([параметры])

{

body

}

<имя> - имя конструктора – название класса

Пример

class A

{

public A(int x, int y) { }

}

class B : A

{

public B(int x, int y) : base(x + y, x - y) { }

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]