theme changed

This commit is contained in:
nik
2025-09-30 08:21:09 +03:00
parent 4c261f7def
commit 8bd93df2ae
917 changed files with 15023 additions and 0 deletions

77
labs/lab8/MyClass/Book.cs Normal file
View File

@@ -0,0 +1,77 @@
using System;
class Book : Item
{
private String author;
private String title;
private String publisher;
private int pages;
private int year;
private bool returnSrok;
private static double price = 9;
static Book()
{
price = 10;
}
public Book()
{
}
public Book(String author, String title, String publisher, int pages, int year, long invNumber, bool taken) : base (invNumber, taken)
{
this.author = author;
this.title = title;
this.publisher = publisher;
this.pages = pages;
this.year = year;
}
public Book(String author, String title)
{
this.author = author;
this.title = title;
}
public void SetBook(String author, String title, String publisher, int pages, int year)
{
this.author = author;
this.title = title;
this.publisher = publisher;
this.pages = pages;
this.year = year;
}
public static void SetPrice(double price)
{
Book.price = price;
}
public override void Show()
{
Console.WriteLine("\nКнига:\n Автор: {0}\n Название: {1}\n Год издания: {2}\n {3} стр.\n Стоимость аренды: {4}", author, title, year, pages, Book.price);
base.Show();
}
public double PriceBook(int s)
{
double cost = s * price;
return cost;
}
public void ReturnSrok()
{
returnSrok = true;
}
public override void Return()
{
taken = returnSrok;
}
}

View File

@@ -0,0 +1,7 @@
using System;
interface IPubs
{
void Subs();
bool IfSubs { get; set; }
}

55
labs/lab8/MyClass/Item.cs Normal file
View File

@@ -0,0 +1,55 @@
using System;
abstract class Item : IComparable
{
protected long invNumber;
protected bool taken;
public Item(long invNumber, bool taken)
{
this.invNumber = invNumber;
this.taken = taken;
}
public Item()
{
this.taken = true;
}
public bool IsAvailable()
{
return taken;
}
public long GetInvNumber()
{
return invNumber;
}
private void Take()
{
taken = false;
}
public void TakeItem()
{
if (this.IsAvailable())
this.Take();
}
abstract public void Return();
public virtual void Show()
{
Console.WriteLine("Состояние единицы хранения:\n Инвентарный номер: {0}\n Наличие: {1}", invNumber, taken);
}
int IComparable.CompareTo(object obj)
{
Item it = (Item)obj;
if (this.invNumber == it.invNumber) return 0;
else if (this.invNumber > it.invNumber) return 1;
else return -1;
}
}

View File

@@ -0,0 +1,40 @@
using System;
class Magazine : Item, IPubs
{
private String volume;
private int number;
private String title;
private int year;
public Magazine(String volume, int number, String title, int year, long invNumber, bool taken) : base(invNumber, taken)
{
this.volume = volume;
this.number = number;
this.title = title;
this.year = year;
}
public Magazine()
{}
public override void Show()
{
Console.WriteLine("\nЖурнал:\n Том: {0}\n Номер: {1}\n Название: {2}\n Год выпуска: {3}", volume, number, title, year);
base.Show();
}
public override void Return()
{
taken = true;
}
public bool IfSubs { get; set; }
public void Subs()
{
Console.WriteLine("Подписка на журнал \"{0}\": {1}.", title, IfSubs);
}
}

View File

@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,77 @@
using System;
public class Program
{
public static void Main(string[] args)
{
Book b1 = new Book();
b1.SetBook("Пушкин А.С.", "Капитанская дочка", "Вильямс", 123, 2012);
Book.SetPrice(12);
b1.Show();
Console.WriteLine("\n Итоговая стоимость аренды: {0} р.", b1.PriceBook(3));
// Book b2 = new Book("Толстой Л.Н.", "Война и мир", "Наука и жизнь", 1234, 2013);
// b2.Show();
Book b3 = new Book("Лермонтов М.Ю.", "Мцыри");
b3.Show();
Triangle t1 = new Triangle(3, 4, 5);
t1.Show();
Console.WriteLine("perimeter = {0}", t1.Perimeter());
Console.WriteLine("area = {0}", t1.Area());
Console.WriteLine("does this triangle exist? {0}", t1.Exists());
Triangle t2 = new Triangle(3, 4, 7);
t2.Show();
Console.WriteLine("does this triangle exist? {0}", t2.Exists());
// Item item1 = new Item();
// item1.Show();
Book b2 = new Book("Толстой Л. Н.", "Война и мир", "Наука и жизнь", 1234, 2013, 101, true);
b2.Show();
b2.TakeItem();
b2.Show();
// Magazine mag1 = new Magazine("О природе", 5, "Земля и мы", 2014, 1235, true);
// mag1.Show();
Console.WriteLine("\n Тестирование полиформизма");
Item it;
it = b2;
it.TakeItem();
it.Return();
it.Show();
// it = mag1;
// it.TakeItem();
// it.Return();
// it.Show();
Magazine mag1 = new Magazine("О природе", 5, "Земля и мы", 2014, 1235, true);
mag1.TakeItem();
mag1.Show();
mag1.IfSubs = true;
mag1.Subs();
Item[] items = new Item[4];
items[0] = b1;
items[1] = b2;
items[2] = b3;
items[3] = mag1;
Array.Sort(items);
Console.WriteLine("\nСортировка по инвентарному номеру");
foreach (Item x in items)
{
x.Show();
}
}
}

View File

@@ -0,0 +1,42 @@
using System;
class Triangle
{
private int a;
private int b;
private int c;
public Triangle(int a, int b, int c)
{
this.a = a;
this.b = b;
this.c = c;
}
public void Show()
{
Console.WriteLine("a: {0}\nb: {1}\nc: {2}", a, b, c);
}
public int Perimeter()
{
return a + b + c;
}
public double Area()
{
double p = Perimeter() / 2;
return Math.Sqrt(p * (p - a) * (p - b) * (p - c));
}
public bool Exists()
{
if (a <= 0 || b <= 0 || c <= 0) return false;
double maxSide = Math.Max(Math.Max(a, b), Math.Max(b, c));
if (maxSide >= a + b + c - maxSide) return false;
return true;
}
}

Binary file not shown.

View File

@@ -0,0 +1,23 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v9.0",
"signature": ""
},
"compilationOptions": {},
"targets": {
".NETCoreApp,Version=v9.0": {
"MyClass/1.0.0": {
"runtime": {
"MyClass.dll": {}
}
}
}
},
"libraries": {
"MyClass/1.0.0": {
"type": "project",
"serviceable": false,
"sha512": ""
}
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,12 @@
{
"runtimeOptions": {
"tfm": "net9.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "9.0.0"
},
"configProperties": {
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
}
}
}

View File

@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v9.0", FrameworkDisplayName = ".NET 9.0")]

View File

@@ -0,0 +1,22 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("MyClass")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+7c0cae85247e714f121496e471ff040abcdf0f0f")]
[assembly: System.Reflection.AssemblyProductAttribute("MyClass")]
[assembly: System.Reflection.AssemblyTitleAttribute("MyClass")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.

View File

@@ -0,0 +1 @@
669a34a9348f9959205ed831232c26c89da1c15b8353ab4f15cece73f33f2362

View File

@@ -0,0 +1,15 @@
is_global = true
build_property.TargetFramework = net9.0
build_property.TargetPlatformMinVersion =
build_property.UsingMicrosoftNETSdkWeb =
build_property.ProjectTypeGuids =
build_property.InvariantGlobalization =
build_property.PlatformNeutralAssembly =
build_property.EnforceExtendedAnalyzerRules =
build_property._SupportedPlatformList = Linux,macOS,Windows
build_property.RootNamespace = MyClass
build_property.ProjectDir = /home/nik/oop/labs/lab8/MyClass/
build_property.EnableComHosting =
build_property.EnableGeneratedComInterfaceComImportInterop =
build_property.EffectiveAnalysisLevelStyle = 9.0
build_property.EnableCodeStyleSeverity =

View File

@@ -0,0 +1,8 @@
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;

View File

@@ -0,0 +1 @@
549f035e7c10aa5d3bdedf5cf21c6bd1a86b89787560e5ea468865b9de0207aa

View File

@@ -0,0 +1,28 @@
/home/nik/oop/labs/lab7/MyClass/bin/Debug/net9.0/MyClass
/home/nik/oop/labs/lab7/MyClass/bin/Debug/net9.0/MyClass.deps.json
/home/nik/oop/labs/lab7/MyClass/bin/Debug/net9.0/MyClass.runtimeconfig.json
/home/nik/oop/labs/lab7/MyClass/bin/Debug/net9.0/MyClass.dll
/home/nik/oop/labs/lab7/MyClass/bin/Debug/net9.0/MyClass.pdb
/home/nik/oop/labs/lab7/MyClass/obj/Debug/net9.0/MyClass.GeneratedMSBuildEditorConfig.editorconfig
/home/nik/oop/labs/lab7/MyClass/obj/Debug/net9.0/MyClass.AssemblyInfoInputs.cache
/home/nik/oop/labs/lab7/MyClass/obj/Debug/net9.0/MyClass.AssemblyInfo.cs
/home/nik/oop/labs/lab7/MyClass/obj/Debug/net9.0/MyClass.csproj.CoreCompileInputs.cache
/home/nik/oop/labs/lab7/MyClass/obj/Debug/net9.0/MyClass.dll
/home/nik/oop/labs/lab7/MyClass/obj/Debug/net9.0/refint/MyClass.dll
/home/nik/oop/labs/lab7/MyClass/obj/Debug/net9.0/MyClass.pdb
/home/nik/oop/labs/lab7/MyClass/obj/Debug/net9.0/MyClass.genruntimeconfig.cache
/home/nik/oop/labs/lab7/MyClass/obj/Debug/net9.0/ref/MyClass.dll
/home/nik/oop/labs/lab8/MyClass/bin/Debug/net9.0/MyClass
/home/nik/oop/labs/lab8/MyClass/bin/Debug/net9.0/MyClass.deps.json
/home/nik/oop/labs/lab8/MyClass/bin/Debug/net9.0/MyClass.runtimeconfig.json
/home/nik/oop/labs/lab8/MyClass/bin/Debug/net9.0/MyClass.dll
/home/nik/oop/labs/lab8/MyClass/bin/Debug/net9.0/MyClass.pdb
/home/nik/oop/labs/lab8/MyClass/obj/Debug/net9.0/MyClass.GeneratedMSBuildEditorConfig.editorconfig
/home/nik/oop/labs/lab8/MyClass/obj/Debug/net9.0/MyClass.AssemblyInfoInputs.cache
/home/nik/oop/labs/lab8/MyClass/obj/Debug/net9.0/MyClass.AssemblyInfo.cs
/home/nik/oop/labs/lab8/MyClass/obj/Debug/net9.0/MyClass.csproj.CoreCompileInputs.cache
/home/nik/oop/labs/lab8/MyClass/obj/Debug/net9.0/MyClass.dll
/home/nik/oop/labs/lab8/MyClass/obj/Debug/net9.0/refint/MyClass.dll
/home/nik/oop/labs/lab8/MyClass/obj/Debug/net9.0/MyClass.pdb
/home/nik/oop/labs/lab8/MyClass/obj/Debug/net9.0/MyClass.genruntimeconfig.cache
/home/nik/oop/labs/lab8/MyClass/obj/Debug/net9.0/ref/MyClass.dll

Binary file not shown.

View File

@@ -0,0 +1 @@
05e67916dc7e7a166b007425dfb5bd2109a5154d4b7f928392676054c8729ea4

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,73 @@
{
"format": 1,
"restore": {
"/home/nik/oop/labs/lab8/MyClass/MyClass.csproj": {}
},
"projects": {
"/home/nik/oop/labs/lab8/MyClass/MyClass.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "/home/nik/oop/labs/lab8/MyClass/MyClass.csproj",
"projectName": "MyClass",
"projectPath": "/home/nik/oop/labs/lab8/MyClass/MyClass.csproj",
"packagesPath": "/home/nik/.nuget/packages/",
"outputPath": "/home/nik/oop/labs/lab8/MyClass/obj/",
"projectStyle": "PackageReference",
"configFilePaths": [
"/home/nik/.nuget/NuGet/NuGet.Config"
],
"originalTargetFrameworks": [
"net9.0"
],
"sources": {
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net9.0": {
"targetAlias": "net9.0",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
},
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "direct"
},
"SdkAnalysisLevel": "9.0.100"
},
"frameworks": {
"net9.0": {
"targetAlias": "net9.0",
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48",
"net481"
],
"assetTargetFallback": true,
"warn": true,
"downloadDependencies": [
{
"name": "Microsoft.AspNetCore.App.Ref",
"version": "[9.0.9, 9.0.9]"
}
],
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "/usr/share/dotnet/sdk/9.0.110/PortableRuntimeIdentifierGraph.json"
}
}
}
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">/home/nik/.nuget/packages/</NuGetPackageRoot>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">/home/nik/.nuget/packages/</NuGetPackageFolders>
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.12.4</NuGetToolVersion>
</PropertyGroup>
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<SourceRoot Include="/home/nik/.nuget/packages/" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />

View File

@@ -0,0 +1,78 @@
{
"version": 3,
"targets": {
"net9.0": {}
},
"libraries": {},
"projectFileDependencyGroups": {
"net9.0": []
},
"packageFolders": {
"/home/nik/.nuget/packages/": {}
},
"project": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "/home/nik/oop/labs/lab8/MyClass/MyClass.csproj",
"projectName": "MyClass",
"projectPath": "/home/nik/oop/labs/lab8/MyClass/MyClass.csproj",
"packagesPath": "/home/nik/.nuget/packages/",
"outputPath": "/home/nik/oop/labs/lab8/MyClass/obj/",
"projectStyle": "PackageReference",
"configFilePaths": [
"/home/nik/.nuget/NuGet/NuGet.Config"
],
"originalTargetFrameworks": [
"net9.0"
],
"sources": {
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net9.0": {
"targetAlias": "net9.0",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
},
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "direct"
},
"SdkAnalysisLevel": "9.0.100"
},
"frameworks": {
"net9.0": {
"targetAlias": "net9.0",
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48",
"net481"
],
"assetTargetFallback": true,
"warn": true,
"downloadDependencies": [
{
"name": "Microsoft.AspNetCore.App.Ref",
"version": "[9.0.9, 9.0.9]"
}
],
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "/usr/share/dotnet/sdk/9.0.110/PortableRuntimeIdentifierGraph.json"
}
}
}
}

View File

@@ -0,0 +1,10 @@
{
"version": 2,
"dgSpecHash": "v60AduM4H1I=",
"success": true,
"projectFilePath": "/home/nik/oop/labs/lab8/MyClass/MyClass.csproj",
"expectedPackageFiles": [
"/home/nik/.nuget/packages/microsoft.aspnetcore.app.ref/9.0.9/microsoft.aspnetcore.app.ref.9.0.9.nupkg.sha512"
],
"logs": []
}

View File

@@ -0,0 +1,23 @@
using System;
class ArithmeticProgression : IProgression
{
private int a0;
private int b;
public ArithmeticProgression(int a0, int b)
{
this.a0 = a0;
this.b = b;
}
public int GetElement(int k)
{
return a0 + (k - 1) * b;
}
public int Sum(int n)
{
return (2 * a0 + (n - 1) * b) * n / 2;
}
}

View File

@@ -0,0 +1,24 @@
using System;
class GeometricProgression : IProgression
{
private int p0;
private int q;
public GeometricProgression(int p0, int q)
{
this.p0 = p0;
this.q = q;
}
public int GetElement(int k)
{
return p0 * (int)Math.Pow(q, k - 1);
}
public int Sum(int n)
{
if (q == 1) return p0 * n;
return p0 * (int)((Math.Pow(q, n) - 1) / (q - 1));
}
}

View File

@@ -0,0 +1,7 @@
using System;
interface IProgression
{
int GetElement(int k);
int Sum(int n);
}

View File

@@ -0,0 +1,18 @@
using System;
public class Program
{
public static void Main(string[] args)
{
IProgression arith = new ArithmeticProgression(2, 3);
IProgression geom = new GeometricProgression(2, 2);
Console.WriteLine("Арифметическая прогрессия:");
Console.WriteLine("5-й элемент = " + arith.GetElement(5));
Console.WriteLine("Сумма 5 элементов = " + arith.Sum(5));
Console.WriteLine("\nГеометрическая прогрессия:");
Console.WriteLine("5-й элемент = " + geom.GetElement(5));
Console.WriteLine("Сумма 5 элементов = " + geom.Sum(5));
}
}

View File

@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

Binary file not shown.

View File

@@ -0,0 +1,23 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v9.0",
"signature": ""
},
"compilationOptions": {},
"targets": {
".NETCoreApp,Version=v9.0": {
"Progrssion/1.0.0": {
"runtime": {
"Progrssion.dll": {}
}
}
}
},
"libraries": {
"Progrssion/1.0.0": {
"type": "project",
"serviceable": false,
"sha512": ""
}
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,12 @@
{
"runtimeOptions": {
"tfm": "net9.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "9.0.0"
},
"configProperties": {
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
}
}
}

View File

@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v9.0", FrameworkDisplayName = ".NET 9.0")]

View File

@@ -0,0 +1,22 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Progrssion")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+7c0cae85247e714f121496e471ff040abcdf0f0f")]
[assembly: System.Reflection.AssemblyProductAttribute("Progrssion")]
[assembly: System.Reflection.AssemblyTitleAttribute("Progrssion")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.

View File

@@ -0,0 +1 @@
50a88fde13001e552e5a15c4c1dc9d84bf377c2af97397458f32aa7bfb8ed0ce

View File

@@ -0,0 +1,15 @@
is_global = true
build_property.TargetFramework = net9.0
build_property.TargetPlatformMinVersion =
build_property.UsingMicrosoftNETSdkWeb =
build_property.ProjectTypeGuids =
build_property.InvariantGlobalization =
build_property.PlatformNeutralAssembly =
build_property.EnforceExtendedAnalyzerRules =
build_property._SupportedPlatformList = Linux,macOS,Windows
build_property.RootNamespace = Progrssion
build_property.ProjectDir = /home/nik/oop/labs/lab8/Progrssion/
build_property.EnableComHosting =
build_property.EnableGeneratedComInterfaceComImportInterop =
build_property.EffectiveAnalysisLevelStyle = 9.0
build_property.EnableCodeStyleSeverity =

View File

@@ -0,0 +1,8 @@
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;

View File

@@ -0,0 +1 @@
febb35b45ae827ae2cc38bca29142b671a3067babd5d9854467e6c29a7f734b8

View File

@@ -0,0 +1,28 @@
/home/nik/oop/labs/lab7/Progrssion/bin/Debug/net9.0/Progrssion
/home/nik/oop/labs/lab7/Progrssion/bin/Debug/net9.0/Progrssion.deps.json
/home/nik/oop/labs/lab7/Progrssion/bin/Debug/net9.0/Progrssion.runtimeconfig.json
/home/nik/oop/labs/lab7/Progrssion/bin/Debug/net9.0/Progrssion.dll
/home/nik/oop/labs/lab7/Progrssion/bin/Debug/net9.0/Progrssion.pdb
/home/nik/oop/labs/lab7/Progrssion/obj/Debug/net9.0/Progrssion.GeneratedMSBuildEditorConfig.editorconfig
/home/nik/oop/labs/lab7/Progrssion/obj/Debug/net9.0/Progrssion.AssemblyInfoInputs.cache
/home/nik/oop/labs/lab7/Progrssion/obj/Debug/net9.0/Progrssion.AssemblyInfo.cs
/home/nik/oop/labs/lab7/Progrssion/obj/Debug/net9.0/Progrssion.csproj.CoreCompileInputs.cache
/home/nik/oop/labs/lab7/Progrssion/obj/Debug/net9.0/Progrssion.dll
/home/nik/oop/labs/lab7/Progrssion/obj/Debug/net9.0/refint/Progrssion.dll
/home/nik/oop/labs/lab7/Progrssion/obj/Debug/net9.0/Progrssion.pdb
/home/nik/oop/labs/lab7/Progrssion/obj/Debug/net9.0/Progrssion.genruntimeconfig.cache
/home/nik/oop/labs/lab7/Progrssion/obj/Debug/net9.0/ref/Progrssion.dll
/home/nik/oop/labs/lab8/Progrssion/obj/Debug/net9.0/Progrssion.GeneratedMSBuildEditorConfig.editorconfig
/home/nik/oop/labs/lab8/Progrssion/obj/Debug/net9.0/Progrssion.AssemblyInfoInputs.cache
/home/nik/oop/labs/lab8/Progrssion/obj/Debug/net9.0/Progrssion.AssemblyInfo.cs
/home/nik/oop/labs/lab8/Progrssion/obj/Debug/net9.0/Progrssion.csproj.CoreCompileInputs.cache
/home/nik/oop/labs/lab8/Progrssion/obj/Debug/net9.0/Progrssion.dll
/home/nik/oop/labs/lab8/Progrssion/obj/Debug/net9.0/refint/Progrssion.dll
/home/nik/oop/labs/lab8/Progrssion/obj/Debug/net9.0/Progrssion.pdb
/home/nik/oop/labs/lab8/Progrssion/bin/Debug/net9.0/Progrssion
/home/nik/oop/labs/lab8/Progrssion/bin/Debug/net9.0/Progrssion.deps.json
/home/nik/oop/labs/lab8/Progrssion/bin/Debug/net9.0/Progrssion.runtimeconfig.json
/home/nik/oop/labs/lab8/Progrssion/bin/Debug/net9.0/Progrssion.dll
/home/nik/oop/labs/lab8/Progrssion/bin/Debug/net9.0/Progrssion.pdb
/home/nik/oop/labs/lab8/Progrssion/obj/Debug/net9.0/Progrssion.genruntimeconfig.cache
/home/nik/oop/labs/lab8/Progrssion/obj/Debug/net9.0/ref/Progrssion.dll

Binary file not shown.

View File

@@ -0,0 +1 @@
b9720ec9fc833a3887df304a58803c131b5c329c227cb6c752c6888eb7c287f6

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,73 @@
{
"format": 1,
"restore": {
"/home/nik/oop/labs/lab8/Progrssion/Progrssion.csproj": {}
},
"projects": {
"/home/nik/oop/labs/lab8/Progrssion/Progrssion.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "/home/nik/oop/labs/lab8/Progrssion/Progrssion.csproj",
"projectName": "Progrssion",
"projectPath": "/home/nik/oop/labs/lab8/Progrssion/Progrssion.csproj",
"packagesPath": "/home/nik/.nuget/packages/",
"outputPath": "/home/nik/oop/labs/lab8/Progrssion/obj/",
"projectStyle": "PackageReference",
"configFilePaths": [
"/home/nik/.nuget/NuGet/NuGet.Config"
],
"originalTargetFrameworks": [
"net9.0"
],
"sources": {
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net9.0": {
"targetAlias": "net9.0",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
},
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "direct"
},
"SdkAnalysisLevel": "9.0.100"
},
"frameworks": {
"net9.0": {
"targetAlias": "net9.0",
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48",
"net481"
],
"assetTargetFallback": true,
"warn": true,
"downloadDependencies": [
{
"name": "Microsoft.AspNetCore.App.Ref",
"version": "[9.0.9, 9.0.9]"
}
],
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "/usr/share/dotnet/sdk/9.0.110/PortableRuntimeIdentifierGraph.json"
}
}
}
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">/home/nik/.nuget/packages/</NuGetPackageRoot>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">/home/nik/.nuget/packages/</NuGetPackageFolders>
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.12.4</NuGetToolVersion>
</PropertyGroup>
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<SourceRoot Include="/home/nik/.nuget/packages/" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />

View File

@@ -0,0 +1,78 @@
{
"version": 3,
"targets": {
"net9.0": {}
},
"libraries": {},
"projectFileDependencyGroups": {
"net9.0": []
},
"packageFolders": {
"/home/nik/.nuget/packages/": {}
},
"project": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "/home/nik/oop/labs/lab8/Progrssion/Progrssion.csproj",
"projectName": "Progrssion",
"projectPath": "/home/nik/oop/labs/lab8/Progrssion/Progrssion.csproj",
"packagesPath": "/home/nik/.nuget/packages/",
"outputPath": "/home/nik/oop/labs/lab8/Progrssion/obj/",
"projectStyle": "PackageReference",
"configFilePaths": [
"/home/nik/.nuget/NuGet/NuGet.Config"
],
"originalTargetFrameworks": [
"net9.0"
],
"sources": {
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net9.0": {
"targetAlias": "net9.0",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
},
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "direct"
},
"SdkAnalysisLevel": "9.0.100"
},
"frameworks": {
"net9.0": {
"targetAlias": "net9.0",
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48",
"net481"
],
"assetTargetFallback": true,
"warn": true,
"downloadDependencies": [
{
"name": "Microsoft.AspNetCore.App.Ref",
"version": "[9.0.9, 9.0.9]"
}
],
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "/usr/share/dotnet/sdk/9.0.110/PortableRuntimeIdentifierGraph.json"
}
}
}
}

View File

@@ -0,0 +1,10 @@
{
"version": 2,
"dgSpecHash": "+4R2gX25Pfg=",
"success": true,
"projectFilePath": "/home/nik/oop/labs/lab8/Progrssion/Progrssion.csproj",
"expectedPackageFiles": [
"/home/nik/.nuget/packages/microsoft.aspnetcore.app.ref/9.0.9/microsoft.aspnetcore.app.ref.9.0.9.nupkg.sha512"
],
"logs": []
}

BIN
labs/lab8/assets/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

BIN
labs/lab8/assets/2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

BIN
labs/lab8/assets/3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

BIN
labs/lab8/report.pdf Normal file

Binary file not shown.

350
labs/lab8/report.typ Normal file
View File

@@ -0,0 +1,350 @@
#set text(size: 1.3em)
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
// title
#align(center)[Санкт-Петербургский национальный исследовательский университет информационных технологий, механики и оптики]
\
\
\
#align(center)[Факультет инфокоммуникационных технологий]
#align(center)[Направление подготовки 11.03.02]
\
\
#align(center)[Лабораторная работа №8]
#align(center)[Использование интерфейсов при реализации иерархии классов]
\
\
\ //#align(center)[Вариант 19]
\
\
\
\
\
\
\
#align(right)[Выполнил:]
#align(right)[Дощенников Никита Андреевич]
#align(right)[Группа: К3221]
#align(right)[Проверил:]
#align(right)[Иванов Сергей Евгеньевич]
\
\
#align(center)[Санкт-Петербург]
#align(center)[2025]
#pagebreak()
=== Цель работы:
Использовать интерфейсы при реализации иерархии классов как важного элемента объектно-ориентированного программирования и приобретение навыков реализации интерфейсов.
=== Упражнение 1. Создание и реализация интерфейса.
В этом упражнении я создал интерфейс, определяющий поведение классов, которые будут его реализовывать.
```cs
using System;
interface IPubs
{
void Subs();
bool IfSubs { get; set; }
}
```
```cs
using System;
class Magazine : Item, IPubs
{
private String volume;
private int number;
private String title;
private int year;
public Magazine(String volume, int number, String title, int year, long invNumber, bool taken) : base(invNumber, taken)
{
this.volume = volume;
this.number = number;
this.title = title;
this.year = year;
}
public Magazine()
{}
public override void Show()
{
Console.WriteLine("\nЖурнал:\n Том: {0}\n Номер: {1}\n Название: {2}\n Год выпуска: {3}", volume, number, title, year);
base.Show();
}
public override void Return()
{
taken = true;
}
public bool IfSubs { get; set; }
public void Subs()
{
Console.WriteLine("Подписка на журнал \"{0}\": {1}.", title, IfSubs);
}
}
```
Тесты:
```cs
public static void Main(string[] args)
{
Magazine mag1 = new Magazine("О природе", 5, "Земля и мы", 2014, 1235, true);
mag1.TakeItem();
mag1.Show();
mag1.IfSubs = true;
mag1.Subs();
}
```
Пример:
#align(center)[#image("assets/1.png")]
=== Упражнение 2. Использование стандартных интерфейсов.
В этом упражнении я применил интерфейс `IComparable`, который задает метод сравнения объектов по принципу больше и меньше, что позволяет переопределить соответствующие операции в рамках класса, наследующего интерфейс `IComparable`.
```cs
using System;
abstract class Item : IComparable
{
protected long invNumber;
protected bool taken;
public Item(long invNumber, bool taken)
{
this.invNumber = invNumber;
this.taken = taken;
}
public Item()
{
this.taken = true;
}
public bool IsAvailable()
{
return taken;
}
public long GetInvNumber()
{
return invNumber;
}
private void Take()
{
taken = false;
}
public void TakeItem()
{
if (this.IsAvailable())
this.Take();
}
abstract public void Return();
public virtual void Show()
{
Console.WriteLine("Состояние единицы хранения:\n Инвентарный номер: {0}\n Наличие: {1}", invNumber, taken);
}
int IComparable.CompareTo(object obj)
{
Item it = (Item)obj;
if (this.invNumber == it.invNumber) return 0;
else if (this.invNumber > it.invNumber) return 1;
else return -1;
}
}
```
Тесты:
```cs
public static void Main(string[] args)
{
Item[] items = new Item[4];
items[0] = b1;
items[1] = b2;
items[2] = b3;
items[3] = mag1;
Array.Sort(items);
Console.WriteLine("\nСортировка по инвентарному номеру");
foreach (Item x in items)
{
x.Show();
}
}
```
Пример:
#align(center)[#image("assets/2.png")]
=== Упражнение 3. Реализация прогрессии с помощью интерфейса.
В этом упражнении я заменил абстрактный класс `Progression` на интерфейс `IProgression`, определяющий поведение классов `ArithmeticProgression` и `GeometricProgression`, описывающих арифметическую и геометрическую прогрессии.
```cs
using System;
interface IProgression
{
int GetElement(int k);
int Sum(int n);
}
```
```cs
using System;
class ArithmeticProgression : IProgression
{
private int a0;
private int b;
public ArithmeticProgression(int a0, int b)
{
this.a0 = a0;
this.b = b;
}
public int GetElement(int k)
{
return a0 + (k - 1) * b;
}
public int Sum(int n)
{
return (2 * a0 + (n - 1) * b) * n / 2;
}
}
```
```cs
using System;
class GeometricProgression : IProgression
{
private int p0;
private int q;
public GeometricProgression(int p0, int q)
{
this.p0 = p0;
this.q = q;
}
public int GetElement(int k)
{
return p0 * (int)Math.Pow(q, k - 1);
}
public int Sum(int n)
{
if (q == 1) return p0 * n;
return p0 * (int)((Math.Pow(q, n) - 1) / (q - 1));
}
}
```
Тесты:
```cs
public static void Main(string[] args)
{
IProgression arith = new ArithmeticProgression(2, 3);
IProgression geom = new GeometricProgression(2, 2);
Console.WriteLine("Арифметическая прогрессия:");
Console.WriteLine("5-й элемент = " + arith.GetElement(5));
Console.WriteLine("Сумма 5 элементов = " + arith.Sum(5));
Console.WriteLine("\nГеометрическая прогрессия:");
Console.WriteLine("5-й элемент = " + geom.GetElement(5));
Console.WriteLine("Сумма 5 элементов = " + geom.Sum(5));
}
```
Пример:
#align(center)[#image("assets/3.png")]
=== Выводы.
В ходе проделанной лабораторной работы я использовал интерфейсы при реализации иерархии классов как важного элемента объектно-ориентированного программирования и приобретел навыки реализации интерфейсов.
=== Code review. (by #link("https://zzzcode.ai")[zzzcode.ai])
*Резюме*
Класс `Book` представляет собой реализацию книги с различными атрибутами, такими как автор, название, издатель и т.д. Он наследуется от абстрактного класса `Item`, который управляет состоянием доступности книги. Код в целом хорошо структурирован, но требует некоторых улучшений в области стиля и производительности.
*Ошибка*
В методе `Return()` класса `Book` переменная `taken` устанавливается в значение `returnSrok`, которое по умолчанию равно `false`. Это может привести к тому, что книга будет считаться возвращенной, даже если она не была возвращена. Следует добавить логику для проверки состояния возврата.
*Стиль кода*
Использование `String` вместо `string` не соответствует общепринятому стилю C\#. Рекомендуется использовать `string` (с маленькой буквы). Имена переменных и методов должны следовать соглашениям о наименовании. Например, `returnSrok` можно переименовать в `isReturned` для большей ясности.
*Структура кода*
Класс `Book` имеет хорошую структуру, однако: Конструкторы перегружены, что может усложнить создание объектов. Рекомендуется использовать один конструктор с параметрами по умолчанию. Метод `SetBook` можно заменить на использование свойств, что улучшит инкапсуляцию.
*Читаемость*
Код читаем, но можно улучшить: Добавить XML-комментарии к методам и классам для лучшего понимания их назначения. Разделить длинные строки на несколько строк для повышения читаемости.
*Производительность*
Статическая переменная `price` может быть изменена через метод `SetPrice`, что может привести к неожиданным изменениям. Рекомендуется сделать её свойством только для чтения или использовать паттерн Singleton для управления ценой.
*Масштабируемость*
Класс `Book` может быть расширен для поддержки дополнительных атрибутов, таких как жанр или ISBN. Однако, если количество атрибутов увеличится, стоит рассмотреть возможность использования паттерна проектирования, такого как `Builder`.
*Безопасность*
Необходимо добавить валидацию входных данных в конструкторах и методах, чтобы предотвратить создание объектов с некорректными значениями (например, отрицательное количество страниц или год).
*Обработка ошибок*
В текущем коде отсутствует обработка исключений. Рекомендуется добавить обработку ошибок, особенно в методах, которые могут вызывать исключения, таких как `PriceBook`.
*Заключение*
Класс `Book` и его реализация в целом являются хорошей основой для работы с книгами. Однако, для улучшения качества кода и его поддержки, необходимо внести изменения в стиль, структуру и обработку ошибок. Рекомендуется также рассмотреть возможность добавления тестов для проверки функциональности классов.