ОП Т.795.011
Учащийся А.А.Гром
2020
Содержание
Введение 3
1 Объектно-ориентированное программирование с использованием языка C# 4
1.1 Организация циклов 4
1.2 Массивы 5
1.3 Базовые операции над строками 6
1.4 Регулярные выражения 7
1.5 Структуры 8
1.6 Простейшие классы 11
1.7 Классы и операции 13
1.8 Наследование 14
1.9 Делегаты, события, лямбда-выражения 14
1.10 Коллекции 23
1.11 Интерфейсы 24
1.12 Обобщения 25
1.13 LINQ 26
1.14 Работа с объектами файловой системы 28
2 Разработка приложений средствами библиотеки классов MicrosoftNETFramework
30
3 Программирование быстродействующих информационных систем 34
Заключение 39
Список информационных источников 40
ОП Т.795011
Изм. Лист № докум. Подпись Дата
Разраб. Гром А.А. Лит. Лист Листов
Провер. Михалевич 2 40
Отчет по учебной практике по
Т. контр. В.Ю. 2
программированию
Н. контр. КБП
Утверд.
Введение
3
1 Объектно-ориентированное программирование с использованием
языка C#
if (num >= 2) {
if (i % 2 != 0)
if (i % 3 != 0)
if (i % 5 == 0)
Console.WriteLine("\n" + i);
else Console.WriteLine(i);
return i;
return num;
int num = 0;
4
for(int i = 0; k != 0 && i < count; k /= 10, ++i)
num = k % 10;
return num;
int num = 0;
num = k % 10;
return num;
1.2 Массивы
{
5
for (int i = 0, j = 0; i != arr.Length; ++i)
{
{
result[j++] = arr[i];
}
}
return result;
struct MARSH
{
}
class Program
{
private static string InputValue(string message)
{
Console.WriteLine(message);
return Console.ReadLine();
}
Console.WriteLine("\nИнформация в базе:");
}
Console.ReadKey();
}
}
1.6 Простейшие классы
using System;
using System.Collections.Generic;
using System.Linq;
namespace Practica
{
class Program
{
public class Book {
private string name;
private int price;
private string genre;
private int quantity;
8
public string Name
{
get
{
return name;
}
set
{
if (value.Length < 0)
{
throw new Exception("Error");
}
name = value;
}
}
set
{
if (value < 0)
{
throw new Exception("Error");
}
price = value;
}
}
set
{
if(value.Length < 0)
9
{
throw new Exception("Error");
}
genre = value;
}
}
~Rectangle()
{
Console.WriteLine("Уничтожен");
}
}
}
1.8 Наследование
class Item
{
protected int invNumber;
protected bool taken;
12
public virtual void show()
{
Console.WriteLine($"Инвертарный номер {invNumber}");
Console.WriteLine($"Взята: {taken}");
}
public bool isAvaliable()
{
return taken == false;
}
public int getInvNumber()
{
return invNumber;
}
public void takeBook()
{
if (taken == false)
{
taken = true;
Console.WriteLine($"Книга с инвертарным номером {invNumber}
была взята");
}
else
{
Console.WriteLine($"Книга с инвертарным номером {invNumber}
уже взята!");
}
}
public void returnBook()
{
taken = false;
Console.WriteLine("Книга с инвертарным номером успешно
возвращена!");
}
public Item(int invNumber, bool taken)
{
this.invNumber = invNumber;
this.taken = taken;
}
}
class Book : Item, IShowInfo, ISort<Book>, IPolezniy
{
protected string author;
protected string title;
protected string publisher;
public int year;
13
public string getAuthor()
{
return author;
}
public string getTitle()
{
return title;
}
public string getPublisher()
{
return publisher;
}
public int getYear()
{
return year;
}
public void AddYear(int year)
{
this.year = year;
}
public static int CompareYear(Book a, Book b)
{
//Book b = (Book)obj;
return a.year.CompareTo(b.year);
}
public void SortByYear(Book[] array)
{
for (int i = 1; i < array.Length; i++)
{
Book cur = array[i];
int j = i;
while (j > 0 && cur.year < array[j - 1].year)
{
array[j] = array[j - 1];
j--;
}
array[j] = cur;
}
}
public override void show()
{
Console.WriteLine($"Автор {author}");
Console.WriteLine($"Название: {title}");
Console.WriteLine($"Издатель {publisher}");
Console.WriteLine($"Год издания: {year}");
14
Console.WriteLine($"Взята: {taken}");
}
public void AlertYear()
{
Console.WriteLine(year);
}
public void AlertBookInfo()
{
Console.WriteLine("");
Console.WriteLine("{title} - {author}. Издано в {year} году");
Console.WriteLine("");
}
public void TakenInfo()
{
if (taken)
Console.WriteLine($"Книга {title} взята");
else
Console.WriteLine($"Книга {title} не взята");
}
public Book(string author, string title, string publisher, int year, int
invNumber, bool taken) : base(invNumber, taken)
{
this.author = author;
this.title = title;
this.publisher = publisher;
this.year = year;
}
}
class Shop : Item
{
protected int volume;
protected string title;
protected int number;
protected int year;
private int getVolume()
{
return volume;
}
private string getTitle()
{
return title;
}
private int getNumber()
{
return number;
15
}
private int getYear()
{
return year;
}
public Shop(int volume, string title, int number, int year, int invNumber,
bool taken) : base(invNumber, taken)
{
this.volume = volume;
this.title = title;
this.number = number;
this.year = year;
}
}
Рисунок 1
using System;
using System.Text.RegularExpressions;
namespace _15._1_ПП
{
delegate double Result(double x);
public delegate void Comp(int x, int y);
delegate int Operation(int x, int y);
class Program
{
class BookShielfEventArgs
{
public string Message { get; }
public int BooksNew { get; }
16
public BookShielfEventArgs(string mes, int bk)
{
Message = mes;
BooksNew = bk;
}
public BookShielfEventArgs(string mes)
{
Message = mes;
}
private static void DisplayMessage(string message)
{
Console.WriteLine(message);
}
}
class BookShielf
{
public delegate void BookHandler(object sender, BookShielfEventArgs
e);
public event BookHandler Notify;
private int books;
public int Books
{
get
{
return books;
}
set
{
if(value <= 0)
{
throw new Exception("Количество книг не может быть
меньше или равно 0!");
}
else if (books + value <= maxBooks)
{
books += value;
Notify?.Invoke(this, new BookShielfEventArgs($"{value} книг
были успешно добавлены. Теперь в шкафу {books} книг", value));
}
else if(books + value > maxBooks)
{
Console.WriteLine($"\n Максимально можно положить
{maxBooks - books} книг, а вы кладете {value}!\n");
throw new Exception("ERROR: Количество книг
недопустимо");
17
}
}
}
private int maxBooks;
public int MaxBooks
{
get
{
return maxBooks;
}
set
{
maxBooks = value;
}
}
public BookShielf(int Books, int MaxBooks)
{
this.Books = Books;
this.MaxBooks = MaxBooks;
Notify?.Invoke(this, new BookShielfEventArgs($"Класс был
успешно создан", 0));
}
public BookShielf() { Notify?.Invoke(this, new
BookShielfEventArgs($"Класс был успешно создан")); }
public void ShowInfo()
{
Console.WriteLine("");
Console.WriteLine($"В шкафу лежит {books} книг из {maxBooks}
возможных");
Console.WriteLine("");
}
public void AddBooks(int bookss)
{
this.Books = bookss;
}
}
static void Main(string[] args)
{
// Задание 1
string[] arrayString = new string[5] { "Helfow32", "grferf",
"rgrwer4", "GSEKFJ", "bekrgke42" };
string[] numStringArray = new string[CountNums(arrayString)];
int counter = 0;
for (int i = 0; i < arrayString.Length; i++)
{
18
for (int j = 0; j < arrayString[i].Length; j++)
{
if (arrayString[i][j] == '1' || arrayString[i][j] == '2' ||
arrayString[i][j] == '3' || arrayString[i][j] == '4' || arrayString[i][j] == '5' ||
arrayString[i][j] == '6' || arrayString[i][j] == '7' || arrayString[i][j] == '8' ||
arrayString[i][j] == '9' || arrayString[i][j] == '0')
{
numStringArray[counter] = arrayString[i];
j = arrayString[i].Length;
counter++;
}
}
}
counter = 0;
for (int i = 0; i < arrayString.Length; i++)
{
string now = arrayString[i];
for (int j = 0; j < now.Length; j++)
{
if (now[j] == '1' || now[j] == '2' || now[j] == '3' || now[j] ==
'4' || now[j] == '5' || now[j] == '6' || now[j] == '7' || now[j] == '8' || now[j] == '9' ||
now[j] == '0')
{
j = now.Length - 1;
numStringArray[counter] = arrayString[i];
counter++;
}
}
}
string[] noRegist = new string[CountWords(arrayString)];
Regex regex = new Regex(@"\b([a-z])+\b");
for (int i = 0; i < arrayString.Length; i++)
{
MatchCollection matches = regex.Matches(arrayString[i]);
for (int j = 0; j < matches.Count; j++)
{
noRegist[j] = Convert.ToString(matches[j]);
}
}
string[] result = new string[CountWords(arrayString) +
CountNums(arrayString)];
SetResultArray(result, numStringArray, noRegist);
WriteArray(result);
bool isEnd = false;
while (!isEnd)
19
{
Console.WriteLine("Выберите действие:");
Console.WriteLine("1 - Вывести массив");
Console.WriteLine("2 - Отсортировать массив");
Console.WriteLine("0 - Выйти из меню");
string userInput = Console.ReadLine();
switch (userInput)
{
case "1": WriteArray(result); break;
case "2": Array.Sort(result); break;
case "0": isEnd = true; break;
}
}
Comp comp;
comp = CompateNums;
Console.WriteLine("Введите два числа");
string a = Console.ReadLine();
string b = Console.ReadLine();
Regex regex = new Regex(@",");
MatchCollection matches = regex.Matches(a);
MatchCollection matches_2 = regex.Matches(b);
if (matches.Count >= 1 || matches_2.Count >= 1)
Console.WriteLine("Одно из чисел - составное");
else
comp(Convert.ToInt32(a), Convert.ToInt32(b));*/
1.10 Коллекции
1.11 Интерфейсы
interface ISquare
{
void Square();
int HalfP();
int P();
int HalfLine(int a);
}
class Triangle : ISquare
{
private int a;
private int b;
private int c;
public void Square()
{
Console.WriteLine($"Площадь равна {HalfP() * (HalfP() - a) *
(HalfP() - b) * (HalfP() - c)}");
}
public int HalfP()
{
return (a + b + c) / 2;
}
public int P()
{
return HalfP() + HalfP();
}
public int HalfLine(int a)
{
return a / 2;
}
public Triangle (int a, int b, int c)
{
this.a = a;
this.b = b;
this.c = c;
}
}
24
1.12 Обобщения
25
2 Разработка приложений средствами библиотеки классов
Microsoft .NET Framework
interface IShowInfo
{
void show();
}
interface IAdd
{
int AddYear(int year);
}
interface ISort<T>
{
void SortByYear(T[] array);
}
class Item
{
protected int invNumber;
protected bool taken;
public virtual void show()
{
Console.WriteLine($"Инвертарный номер {invNumber}");
Console.WriteLine($"Взята: {taken}");
}
public bool isAvaliable()
{
return taken == false;
}
public int getInvNumber()
{
return invNumber;
}
public void takeBook()
{
if (taken == false)
{
taken = true;
Console.WriteLine($"Книга с инвертарным номером {invNumber}
была взята");
}
else
{
Console.WriteLine($"Книга с инвертарным номером {invNumber}
уже взята!");
}
26
}
29
3 Программирование быстродействующих информационных систем
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
namespace XmlFormat
{
[Serializable]
class Array
{
public Array(int[] numbers)
{
array = numbers;
}
public int countNegatives()
{
return array.Count((x) => x > 0);
}
public int sumElemsOnEvenPos()
{
return array.Where((x, idx) => idx % 2 == 0).Sum();
}
private int[] array;
}
class DoubleArray
{
public DoubleArray(int[,] numbers)
{
this.numbers = numbers;
}
30
for (int i = 0; i < numbers.GetLength(0); ++i)
{
for (int j = 0; j < numbers.GetLength(1); ++j)
{
if (numbers[i, j] < 0)
{
++count;
}
}
}
return count;
}
31
class Program
{
static void Main(string[] args)
{
Array array = new Array(new int[] { 1,2,3,10,22,15,6,4});
Console.WriteLine("Объект создан");
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream fs = new FileStream("./XmlFormat.dat",
FileMode.OpenOrCreate))
{
formatter.Serialize(fs, array);
Console.WriteLine("Объект сериализован");
}
Console.WriteLine("Объект десериализован");
Console.WriteLine();
}
Console.ReadLine();
}
}
}
using System;
using System.Xml;
namespace XmlFormatter
{
class Program
{
static void Main(string[] args)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("./array.xml");
// получим корневой элемент
XmlElement xRoot = xDoc.DocumentElement;
// обход всех узлов в корневом элементе
foreach (XmlNode xnode in xRoot)
32
{
// получаем атрибут name
if (xnode.Attributes.Count > 0)
{
XmlNode attr = xnode.Attributes.GetNamedItem("name");
if (attr != null)
Console.WriteLine(attr.Value);
}
// обходим все дочерние узлы элемента user
foreach (XmlNode childnode in xnode.ChildNodes)
{
// если узел - company
if (childnode.Name == "company")
{
Console.WriteLine($"Компания: {childnode.InnerText}");
}
// если узел age
if (childnode.Name == "age")
{
Console.WriteLine($"Возраст: {childnode.InnerText}");
}
}
Console.WriteLine();
}
Console.Read();
}
}
}
33
Заключение
34
Список информационных источников
9 Стиллмен, Э. Изучаем C# / Э. Стиллмен, Дж. Грин. – 3-е изд. – СПб.: Питер, 2014.
– 816 с.: ил.
12 Шарп, Джон. Microsoft Visual C#. Подробное руководство / Джон Шарп. – 8-е изд.
– – СПб.: Питер, 2017. – 848 с.: ил.
35