Объекты и типы

Содержание

Слайд 2

доступ возвращаемый_тип методN(список_параметров) { // тело метода } } struct имя_структуры

доступ возвращаемый_тип методN(список_параметров)
{
// тело метода
}
}
struct имя_структуры [:

интерфейсы]
{
// Объявления переменных экземпляра
доступ тип переменная1;
доступ тип переменная2;
// . . .
доступ тип переменнаяN;
// Объявления методов
доступ возвращаемый_тип метод1(список_параметров)
{
// тело метода
}
Слайд 3

доступ возвращаемый_тип метод2(список_параметров) { // тело метода } // . .

доступ возвращаемый_тип метод2(список_параметров)
{
// тело метода
}
// .

. .
доступ возвращаемый_тип методN(список_параметров)
{
// тело метода
}
}
Слайд 4

1) class PhoneCustomer { public const string DayOfSendingBill = "Monday"; public

1)
class PhoneCustomer
{
public const string DayOfSendingBill = "Monday";
public

int CustomerlD;
public string FirstName;
public string LastName;
}
2)
struct PhoneCustomerStruct
{
public const string DayOfSendingBill = "Monday";
public int CustomerlD;
public string FirstName;
public string LastName;
}
3)
PhoneCustomer myCustomer = new PhoneCustomer();
// работает с классом
PhoneCustomerStruct myCustomer2 = new PhoneCustomerStruct();
// работает со структурой
Слайд 5

4) PhoneCustomer Customer1 = new PhoneCustomer (); Customer1.FirstName = "Simon"; 5)

4)
PhoneCustomer Customer1 = new PhoneCustomer ();
Customer1.FirstName = "Simon";
5)
class PhoneCustomer
{

public const string DayOfSendingBill = "Monday";
public int CustomerID; public string FirstName;
public string LastName;
}
6)
[модификаторы] тип_возврата ИмяМетода([параметры])
{
// Тело метода
}
7)
public bool IsSquare(Rectangle rect)
{
return (rect.Height == rect.Width);
}
Слайд 6

8) public bool IsPositive(int value) ; { if (value return false;

8)
public bool IsPositive(int value) ;
{
if (value < 0)
return false;

return true;
}
9)
using System;
namespace Wrox
{
class MainEntryPoint
{
static void Main()
{
// Try calling some static functions
Console.WriteLine("Pi is " + MathTest.GetPi());
int x = MathTest.GetSquareOf(5);
Console.WriteLine("Square of 5 is " + x);
Слайд 7

// Instantiate at MathTest object MathTest math = new MathTest(); //

// Instantiate at MathTest object
MathTest math = new MathTest();

// this is C#'s way of
// instantiating a reference type
// Call non-static methods
math.Value = 30;
Console.WriteLine(
"Value field of math variable contains " + math.Value);
Console.WriteLine("Square of 30 is " + math.GetSquare());
}
}
// Define a class named MathTest on which we will call a method
class MathTest
{
public int Value;
public int GetSquare()
{
return Value*Value;
}
Слайд 8

public static int GetSquareOf(int x) { return x*x; } public static

public static int GetSquareOf(int x)
{
return x*x;
}
public

static double GetPi()
{
return 3.14159;
}
}
}
10)
Pi равно 3.14159
5 в квадрате равно 25
Поле value переменной math содержит 30
30 в квадрате равно 900
11)
using System;
namespace Wrox
{
Слайд 9

class ParameterTest { static void SomeFunction(int[] ints, int i) { ints[0]

class ParameterTest
{
static void SomeFunction(int[] ints, int i)
{
ints[0]

= 100;
i = 100;
}
public static int Main()
{
int i = 0;
int[] ints = { 0, 1, 2, 4, 8 };
// Display the original values
Console.WriteLine("i = " + i);
Console.WriteLine("ints[0] = " + ints[0]);
Console.WriteLine("Calling SomeFunction...");
// After this method returns, ints will be changed,
// but i will not
SomeFunction(ints, i);
Console.WriteLine("i = " + i);
Console.WriteLine("ints[0] = " + ints[0]);
Слайд 10

return 0; } } } 12) ParameterTest.exe i = 0 ints[0)

return 0;
}
}
}
12)
ParameterTest.exe i = 0
ints[0) = 0
Вызов SomeFunction...
i

= 0
ints[0] = 100
13)
static void SomeFunction (int [ ] ints, ref int i)
{
ints[0] = 100;
i = 100;
// изменение i сохранится после завершения SomeFunction ()
}
14)
SomeFunction(ints, ref i);
Слайд 11

15) static void SomeFunction (out int i) { i = 100;

15)
static void SomeFunction (out int i)
{
i = 100;
}
public static

int Main()
{
int i; // переменная i объявлена, но не инициализирована
SomeFunction(out i);
Console.WriteLine(i);
return 0;
}
16)
string FullName(string firstName, string lastName)
{
return firstName + " " + lastName;
}
17)
FullName("John", "Doe");
FullName(lastName: "Doe", firstName: "John");
Слайд 12

18) void TestMethod(int optionalNumber = 10, int notOptionalNumber) { System.Console.Write(optionalNumber +

18)
void TestMethod(int optionalNumber = 10, int notOptionalNumber)
{
System.Console.Write(optionalNumber + notOptionalNumber);
}
19)
class

ResultDisplayer
{
void DisplayResult(string result)
{
// реализация
}
void DisplayResult(int result)
{
// реализация
}
}
Слайд 13

20) class MyClass { int DoSomething(int x) // нужен 2-й параметр

20)
class MyClass
{
int DoSomething(int x)
// нужен 2-й параметр

со значением по умолчанию 10
{
DoSomething(х, 10);
}
int DoSomething(int x, int y)
{
// реализация
}
}
21)
// mainForm относится к типу System.Windows.Forms
mainForm.Height = 400;
Слайд 14

тип_элемента this[int индекс] { // Аксессор для получения данных get {

тип_элемента this[int индекс]
{
// Аксессор для получения данных
get


{
// Возврат значения, которое определяет индекс.
}
// Аксессор для установки данных
set
{
// Установка значения, которое определяет индекс.
}
}
Листинг 1
// Использовать индексатор для создания отказоустойчивого массива
using System;
Слайд 15

class FailSoftArray { int[] a; // ссылка на базовый массив public

class FailSoftArray
{
int[] a; // ссылка на базовый массив


public int Length; // открытая переменная длины массива
public bool ErrFlag; // обозначает результат последней операции
// Построить массив заданного размера
public FailSoftArray(int size)
{
a = new int[size];
Length = size;
}
// Это индексатор для класса FailSoftArray
public int this[int index] {
// Это аксессор get
get
{
Слайд 16

if(ok(index)) { ErrFlag = false; return a[index]; } else { ErrFlag

if(ok(index)) {
ErrFlag = false;
return a[index];

} else {
ErrFlag = true;
return 0;
}
}
// Это аксессор set
set
{
if(ok(index))
{
a[index] = value;
ErrFlag = false;
}
else ErrFlag = true;
}
}
Слайд 17

// Возвратить логическое значение true, если // индекс находится в установленных

// Возвратить логическое значение true, если
// индекс находится в установленных

границах
private bool ok(int index)
{
if(index >= 0 & index < Length) return true;
return false;
}
}
// Продемонстрировать применение отказоустойчивого массива
class FSDemo
{
static void Main()
{
FailSoftArray fs = new FailSoftArray(5);
int x;
// Выявить скрытые сбои
Console.WriteLine("Скрытый сбой.");
for(int i=0; i < (fs.Length * 2); i++)
fs[i] = i*10;
Слайд 18

for(int i=0; i { x = fs[i]; if(x != -1) Console.Write(x

for(int i=0; i < (fs.Length * 2); i++)
{


x = fs[i];
if(x != -1) Console.Write(x + " ");
}
Console.WriteLine();
// А теперь показать сбои
Console.WriteLine("\nСбой с уведомлением об ошибках.");
for(int i=0; i < (fs.Length * 2); i++) {
fs[i] = i*10;
if(fs.ErrFlag)
Console.WriteLine("fs[" + i + "] вне границ");
}
for(int i=0; i < (fs.Length * 2); i++) {
x = fs[i];
if(!fs.ErrFlag) Console.Write(x + " ");
else
Console.WriteLine("fs[" + i + "] out-of-bounds");
}
}
}
Слайд 19

Слайд 20

22) public string SomeProperty { get { return "Это значение свойства";

22)
public string SomeProperty
{
get
{
return "Это значение свойства";

}
set
{
// Сделать все необходимое для установки свойства
}
}
23)
private int age;
public int Age
{
get f
{
return age;
}
Слайд 21

set { age = value; } } 24) private string name;

set
{
age = value;
}
}
24)
private string name;
public

string Name
{
get
{
return name;
}
}