I have created the virtual method in the main class, in the heirs of classes, it is overridden. So, I need to take from the classes of heirs the value of variables that are in the override method. I create objects of classes of successors, but I need to enter arguments and here I do not know what to do. Here is the whole code:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.IO; using help3; namespace help3 { public class Katalog { public string Type { get; set; } public string Model { get; set; } public string Firm { get; set; } public string Diagonal { get; set; } public int Tv_tuner { get; set; } public string Resolution { get; set; } public string Type_matrix { get; set; } public string Type_sensor { get; set; } //Sensor public string Amount_hdd { get; set; } //Sensor public virtual int Price() { int value = 0; return value; } } public class LCD : Katalog { public int value { get; set; } public LCD(string Type, string Model, string Firm, string Diagonal, int Tv_Tuner, string Resolution, string Type_matrix, int value) { this.Type = Type; this.Model = Model; this.Firm = Firm; this.Diagonal = Diagonal; this.Tv_tuner = Tv_tuner; this.Resolution = Resolution; this.Type_matrix = Type_matrix; this.value = value; } public LCD(string l) { string[] split = l.Split(new Char[] { '*' }); Model = split[0].Trim(); Firm = split[1].Trim(); Diagonal = split[2].Trim(); Tv_tuner = int.Parse(split[3].Trim()); Resolution = split[4].Trim(); Type_matrix = split[5].Trim(); value = int.Parse(split[6].Trim()); } public override string ToString() { return String.Format("Модель {0}\nФирма {1}\nДиагональ {2}\nРазрешение {3}\nТип матрицы {4}\nСтоимость {5} гривны\n", Model, Firm, Diagonal, Resolution, Type_matrix, value); } public override int Price() { value = (value + Tv_tuner) - (value * 5 / 100); return value; } } public class Sensor : Katalog { public Sensor(string Type, string Model, string Firm, string Diagonal, int Tv_Tuner, string Resolution, string Type_sensor, string Amount_hdd) { this.Type = Type; this.Model = Model; this.Firm = Firm; this.Diagonal = Diagonal; this.Resolution = Resolution; this.Type_sensor = Type_sensor; this.Amount_hdd = Amount_hdd; } public int value { get; set; } public Sensor(string l) { string[] split = l.Split(new Char[] { '*' }); Model = split[0].Trim(); Firm = split[1].Trim(); Diagonal = split[2].Trim(); Resolution = split[3].Trim(); Type_sensor = split[4].Trim(); Amount_hdd = split[5].Trim(); value = int.Parse(split[6].Trim()); } public override string ToString() { return String.Format("Модель {0}\nФирма {1}\nДиагональ {2}\nРазрешение {3}\nOбъем HDD {4}\nТип сенсора {5}\nСтоимость {6} гривны\n", Model, Firm, Diagonal, Resolution, Amount_hdd, Type_sensor, value); } public override int Price() { value = ((value * 3 / 100) * 12 + value) / 12; return value; } } class Program { static void Main(string[] args) { void CreateList() { StreamReader file = new StreamReader("Katalog.txt"); List<LCD> Katalog_LCD = new List<LCD>(); List<Sensor> Katalog_Sensor = new List<Sensor>(); string line; while ((line = file.ReadLine()) != null) { if (line.EndsWith("*")) { Katalog_LCD.Add(new LCD(line)); } else { Katalog_Sensor.Add(new Sensor(line)); } } foreach (LCD a in Katalog_LCD) { Console.WriteLine(a); } foreach (Sensor b in Katalog_Sensor) { Console.WriteLine(b); } } CreateList(); //Программа LCD L = new LCD(); Sensor S = new Sensor(); Console.WriteLine("Какой монитор вы желаете приобрести 1.LCD или 2.Сенсорный?"); string buy; while (true)//Цикл для правильного ввода названия мониторов { buy = Console.ReadLine(); if (buy == "1" || buy == "2") break; else Console.WriteLine("Пожалуйста введите правильное название"); } switch (buy) { case "1": Console.WriteLine("Желаете приопрести ТВ-тюнер всего за 299 гривен и получить скидку 5% на всю сумму покупки?"); string tv_tuner = Console.ReadLine(); if (tv_tuner == "+") { L.Price(); Console.WriteLine("Вы купили LCD монитор и ТВ-тюнер.\nСумма к оплате сo скидкой 5% {0} гривен.", L.value); } else if (tv_tuner == "-") { Console.WriteLine("Вы купили LCD монитор.\nСумма к оплате {0} гривен.", L.value); } break; case "2": Console.WriteLine("Желаете взять кредит на 12 месяцев?"); string kredit = Console.ReadLine(); if (kredit == "+") { Console.WriteLine("Вы взяли кредит, суммой {0} гривен, на 12 месяцев, под 3%.", S.value); S.Price(); Console.WriteLine("Ежемесячная сумма погашения кредита, составляет {0} гривен.", S.value); } else if (kredit == "-") { Console.WriteLine("Вы купили сенсорный монитор. Сумма к оплате {0} гривен.", S.value); } break; } Console.ReadLine(); } } } 

Method creation

Override

Creating class objects

  • one
    remove all code that does not affect the problem so that the example becomes minimal. Try to formulate more precisely what the problem is or what you want to get. So far it is clear that something is wrong with the Price - Grundy method
  • I highlighted everything in the photos. I need to use from the classes of heirs, the value variable, in the main method. How to do it? If you have questions - write, I will try to paint everything clearly. - Nort pm
  • I suspect that the problem is that you have 2 constructors in your descendants classes, which take values, but you create instances of classes referring to empty constructors, which actually are not) - dmepty
  • Well, how to solve this problem? - Nort
  • Either add a constructor that does not accept values ​​and set variables with some standard values, or transfer the necessary parameters to already existing constructors - dmepty

3 answers 3

So, you have a parent class

 public class Katalog { public string Type { get; set; } public string Model { get; set; } public string Firm { get; set; } public string Diagonal { get; set; } public int Tv_tuner { get; set; } public string Resolution { get; set; } public string Type_matrix { get; set; } public string Type_sensor { get; set; } //Sensor public string Amount_hdd { get; set; } //Sensor public virtual int Price() { int value = 0; return value; } } 

And heir class (simplified, so as not to clutter up)

 public class LCD : Katalog { public int Value { get; set; } public LCD() { Type = "*НЕ ЗАДАНО*"; Model = "*НЕ ЗАДАНО*"; Firm = "*НЕ ЗАДАНО*"; Diagonal = "*НЕ ЗАДАНО*"; Tv_tuner = 0; Resolution = "*НЕ ЗАДАНО*"; Type_matrix = "*НЕ ЗАДАНО*"; Value = 0; } public LCD(string Type, string Model, string Firm, string Diagonal, int Tv_Tuner, string Resolution, string Type_matrix, int value) { this.Type = Type; this.Model = Model; this.Firm = Firm; this.Diagonal = Diagonal; this.Tv_tuner = Tv_Tuner; this.Resolution = Resolution; this.Type_matrix = Type_matrix; this.Value = value; } public override int Price() { Value = (Value + Tv_tuner) - (Value * 5 / 100); return Value; } } 

In the class of the heir there is a constructor that does not take values:

 public LCD() { Type = "*НЕ ЗАДАНО*"; Model = "*НЕ ЗАДАНО*"; Firm = "*НЕ ЗАДАНО*"; Diagonal = "*НЕ ЗАДАНО*"; Tv_tuner = 0; Resolution = "*НЕ ЗАДАНО*"; Type_matrix = "*НЕ ЗАДАНО*"; Value = 0; } 

And a constructor that takes values ​​(follows). Next, create instances of the class:

 static void Main(string[] args) { LCD lcd1 = new LCD(); LCD lcd2 = new LCD("qwe","dwdwd","zxcc","dwdwdwdwddddd", 50,"ddgrgrh","dwdbkuk",300); Console.WriteLine(lcd1.Price()); Console.WriteLine(lcd2.Price()); Console.ReadKey(); } 

The lcd1 instance uses the no-parameter constructor, while the lcd2 constructor with parameters.

  • Thank you, you explained quite well, very nicely. You in the creation of the object pass arguments to the constructor in the class, and how do I use the value variable, which is assigned a value from the file and then exists in the class. In theory, I don’t need to transfer anything to the class, the createList method createList already passed everything, on the contrary, I need to take the value of the variable from the class - Nort
  • @Nort You do not have the right vision at the root. In the createList method you have such a line List<LCD> Katalog_LCD = new List<LCD>(); . This Katalog_LCD list of Katalog_LCD type Katalog_LCD . Also this variable is local, that is, you cannot use it outside the method - dmepty
  • @Nort You need to declare this list as global and already carry out these manipulations with it, and then, in main call the price method of this global list - dmepty
  • @Nort You use the concept of a class, but this is not true, the class is the same type as, for example, int , but created by you. It will be correct to operate with the concepts "Instance", "Variable" and then everything will fall into place) - dmepty
  • I understand that List<LCD> Katalog_LCD = new List<LCD>(); local, but in theory it transmits information from a file to an inherited class, to a method in this class, and in a method to an array that already assigns the value to the variable value . Well, in principle, I understand that you are writing, but I do not know how to do it. I did not know about the class account, thanks, and the Instance is the same object, the variable for me is the name of the type created. - Nort

If you answer in the context of your question, then you need to create your own objects:

 LCD L = new LCD(); Sensor S = new Sensor(); 

In accordance with their designers. Or create for them a constructor without parameters. With installation in designers of any values ​​by default.

I also don’t understand the meaning of the createList function. You get two lists of devices from a file, but never use it anywhere. If you want to use these lists in the code below, then you need to organize a cycle, and preferably an iterator. And in general, reduce the device in one list List<Catalog> Katalog = new List<Catalog>(); , using polymorphism, and then determining the type of device through is . By the way, if you use one object, not two, you will be able to get away from the switch , having previously encapsulated messages on the console into class methods.


On the other hand, your architecture is terrible. The inheritance you use is wrong in this case. I would rather use a facade pattern, if of course I managed to understand what you wanted to get. This pattern is described in the design patterns of Eric Freeman.

You can also try to make the differences between the two classes in one common and aggregate abstraction. This can also help a lot.

  • This is a term paper and I need to do everything strictly as I do, nothing else. Using createList I transfer information from a file to an array and output it via a method. - Nort

You can use a variable like this: Take the body of the createList method and createList it into the Main method, and delete the createList method createList . In the method of Main already use the variables and methods of the class. Katalog_LCD[индекс].Price() - start method. Katalog_LCD[индекс].value - use a variable.

But I did it through LINQ, here’s the complete code, who can help someone:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.IO; using help3; namespace help3 { public class Katalog { public string Type { get; set; } public string Model { get; set; } public string Firm { get; set; } public string Diagonal { get; set; } public int Tv_tuner { get; set; } public string Resolution { get; set; } public string Type_matrix { get; set; } public string Type_sensor { get; set; } //Sensor public string Amount_hdd { get; set; } //Sensor public virtual int Price() { int value = 0; return value; } } public class LCD : Katalog { public int value { get; set; } public LCD(string Type, string Model, string Firm, string Diagonal, int Tv_Tuner, string Resolution, string Type_matrix, int value) { this.Type = Type; this.Model = Model; this.Firm = Firm; this.Diagonal = Diagonal; this.Tv_tuner = Tv_tuner; this.Resolution = Resolution; this.Type_matrix = Type_matrix; this.value = value; } public LCD(string l) { string[] split = l.Split(new Char[] { '*' }); Model = split[0].Trim(); Firm = split[1].Trim(); Diagonal = split[2].Trim(); Tv_tuner = int.Parse(split[3].Trim()); Resolution = split[4].Trim(); Type_matrix = split[5].Trim(); value = int.Parse(split[6].Trim()); } public LCD() { } public override string ToString() { return String.Format("Модель {0}\nФирма {1}\nДиагональ {2}\nРазрешение {3}\nТип матрицы {4}\nСтоимость {5} гривны\n", Model, Firm, Diagonal, Resolution, Type_matrix, value); } public override int Price() { value = (value + Tv_tuner) - (value * 5 / 100); return value; } } public class Sensor : Katalog { public int value { get; set; } public Sensor(string l) { string[] split = l.Split(new Char[] { '*' }); Model = split[0].Trim(); Firm = split[1].Trim(); Diagonal = split[2].Trim(); Resolution = split[3].Trim(); Type_sensor = split[4].Trim(); Amount_hdd = split[5].Trim(); value = int.Parse(split[6].Trim()); } public Sensor() { } public override string ToString() { return String.Format("Модель {0}\nФирма {1}\nДиагональ {2}\nРазрешение {3}\nOбъем HDD {4}\nТип сенсора {5}\nСтоимость {6} гривны\n", Model, Firm, Diagonal, Resolution, Amount_hdd, Type_sensor, value); } public override int Price() { value = ((value * 3 / 100) * 12 + value) / 12; return value; } public Sensor(string Type, string Model, string Firm, string Diagonal, int Tv_Tuner, string Resolution, string Type_sensor, string Amount_hdd, int value) { this.Type = Type; this.Model = Model; this.Firm = Firm; this.Diagonal = Diagonal; this.Resolution = Resolution; this.Type_sensor = Type_sensor; this.Amount_hdd = Amount_hdd; this.value = value; } } class Program { static void Main(string[] args) { StreamReader file = new StreamReader("Katalog.txt"); List<LCD> Katalog_LCD = new List<LCD>(); List<Sensor> Katalog_Sensor = new List<Sensor>(); string line; while ((line = file.ReadLine()) != null) { if (line.EndsWith("*")) { Katalog_LCD.Add(new LCD(line)); } else { Katalog_Sensor.Add(new Sensor(line)); } } foreach (LCD a in Katalog_LCD) { Console.WriteLine("---LCD монитор---\n{0}", a);//Вывод ЛСД } foreach (Sensor b in Katalog_Sensor) { Console.WriteLine("---Сенсорный монитор---\n{0}", b);//Вывод Сенсоров } m: string Type; while (true)//Цикл для правильного ввода названия мониторов { Console.WriteLine("Какой тип монитора Вы хотите купить, LCD или Sensor "); Type = Console.ReadLine(); if (Type == "LCD" || Type == "Sensor") break; else Console.WriteLine("Пожалуйста, введите правильный тип"); } Console.WriteLine("Теперь модель монитора"); string Model = Console.ReadLine(); if (Type == "LCD") { var test = from i in Katalog_LCD where i.Model == Model select i; foreach (LCD i in test) { Console.WriteLine("\nВы выбрали этот монитор: \n{0}", i); Console.WriteLine("При покупке LCD монитора с tv-тюнером, стоимостью более 5000 гривен, предоставляется скидка 5%\nСтоимость tv-тюнерa {0} гривен\nЖелатете купить tv-тюнер?", i.Tv_tuner); string tv_tuner = Console.ReadLine(); if (tv_tuner == "+") { if (i.value > 5000) { i.Price(); Console.WriteLine("Вы купили LCD монитор и ТВ-тюнер.\nСумма к оплате сo скидкой {0} гривен.", i.value); } else { Console.WriteLine("Сумма Вашей покупки не достаточна для данyой акции."); } } else if (tv_tuner == "-" && tv_tuner == "+") { Console.WriteLine("Вы купили LCD монитор.\nСумма к оплате {0} гривен.", i.value); } } } else if (Type == "Sensor") { var test = from i in Katalog_Sensor where i.Model == Model select i; foreach (Sensor i in test) { Console.WriteLine("Вы выбрали этот монитор: \n{0}", i); Console.WriteLine("Желаете взять кредит на 12 месяцев?"); string kredit = Console.ReadLine(); if (kredit == "+") { Console.WriteLine("Вы взяли кредит, суммой {0} гривен, на 12 месяцев, под 3%.", i.value); i.Price(); Console.WriteLine("Ежемесячная сумма погашения кредита, составляет {0} гривен.", i.value); } else if (kredit == "-") { Console.WriteLine("Вы купили сенсорный монитор. Сумма к оплате {0} гривен.", i.value); } } } Console.WriteLine("Приходите к нам ещё."); string start = Console.ReadLine(); if (start != null) goto m; Console.ReadLine(); } } }