Skip to content

Conversation

@K-Voland
Copy link

No description provided.

@K-Voland
Copy link
Author

K-Voland commented Dec 2, 2018

Я пока плохо представляю как списки эти работают, но для одинокого кролика оно работает.

@K-Voland
Copy link
Author

K-Voland commented Dec 2, 2018

Вроде что-то начал понимать, теперь оно нормально работает.

public class Rabbit
{
public void RabbitInfo(string Name, string Pearent1,string Pearent2, List<string> Child)
{Console.Write($"Кролик {Name}, Родители: {Pearent1} и {Pearent2}, Дети: ");foreach(var i in Child){Console.WriteLine($"{i} ");}}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Разбейте на несколько строк, читать очень сложно

{
public class Menu:Farm
{
public Rabbit info = new Rabbit();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

имя переменной не информативно - info? но при этом класс кролика

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если это меню, то это толкьо меню!


namespace CourseApp
{
public class Menu:Farm
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут наследование не совсем верно применено - ну или как минимум именование - мен. не является фермой

var krosh = new Rabbit();
var N ="momo";
krosh.RabbitInfo(N);
Assert.Equal("momo",N);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

этот тест не проверяет ващ класс - он только проверяет что переменная N, объявленная в тесте = "momo"

var P1 = "mu";
var P2 = "nu";
krosh.RabbitInfo(N);
Assert.Equal("momo",N);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Та же беда - вы проверяете не свойство класса, а проверяете значение переменных, которые объявлены в тесте

CourseApp/Zoo.cs Outdated
{
public class Zoo
{
public ArrayList Klet = new ArrayList();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Используйте более понятное название - KLet? может Kletka?

CourseApp/Zoo.cs Outdated

set
{
foreach(NewPet i in Klet)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://metanit.com/sharp/tutorial/4.9.php - лучше использовать именно словарь


namespace CourseApp
{
public class Krolik : Zoo
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему кролик наследует зоопарк? Тут с именованием явная беда - при наследовании у нас отошение is-A - "является" . Кролик вряд ли является зоопарком :(

Klet.Add(new NewPet(Name, Pearent1, Pearent2));
foreach(NewPet i in Klet)
{
if(Pearent1 == i.Name || Pearent2 == i.Name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А как же первых добавить?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Покупая в магазине мы не знаем кто родители, потому иногда эти свойства могут отсутствовать.)

CourseApp/Pet.cs Outdated
{
public abstract class Pet
{
private Dictionary<string, NewPet> spisok = new Dictionary<string, NewPet>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Думаю что это уже не список - поэтому лучше называть переменну. так, что это будет отражать сущность

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что-то совсем не приходит ничего в голову. По моему это как раз список животных с их родителями и потомками.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не нужно вам это внутри домашнего животного

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я сейчас залью исправления и открою PR в ваш репозитарий

@K-Voland
Copy link
Author

Проблем много, ещё буду править. Это не окончательная версия, просто хочется услышать комментарии.

@K-Voland
Copy link
Author

Видимо я что-то не понимаю в устройстве записи памяти. Обращаясь к BuyPet из Menu я вроде должен создать новую запись в словаре, но потом когда хочу получить обратно пишет что не найден такой ключ. Что я не так делаю?

public override void BuyPet()
{
Console.Write("Введите имя купленного кролика: ");
Name = Console.ReadLine();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не не - это - плохая идея - обработку пользовательского ввода вести в классахз, фактически представляюзих модели данных - уберите, а Name передавайте как параметр метода. И сразу подумайте - а как это протестировать?


public override void NewPet()
{
Console.Write("Введите имя новорожденного кролика: ");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

то же самое - вынесите в основную программу получение параметров, а здесь, только их проверьте

Vid = Console.ReadLine();
if (Vid == "rabbit")
{
krosh.BuyPet();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если вы даете пользователю выбрать что купить... то почему не создать ресурся здесь а не выше (экземпляры классов) - и вызовутся только тогда, когда пользователь определиться - кроша или кролика

}

break;
case "Sel":
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тут так просто не разобраться, попробую завтра переписать по другому


namespace CourseApp
{
public class NewPet : Pet
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень плохое название NewPet создается вот так - new Pet(), а тут все таки какая то иерархия

CourseApp/Pet.cs Outdated

public List<string> Child { get => child; set => child = value; }

public string Vid {get; set; }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe Type?

{
public class Cavy : AbstractPet
{
public override void BuyPet()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не дело морской свинки продавать домашние животные :)


public override void NewPet()
{
Console.Write("Введите имя новорожденной морской свинки: ");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Осуществлять пользовательский ввод тоже не надо в классах, которые представляют сущности

public override void NewPet()
{
Console.Write("Введите имя новорожденной морской свинки: ");
Name = Console.ReadLine();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот для всего этого есть порождающий паттерн фабрика. или фабричный метод - как раз для реализации вашей идеи

{
Console.Write("Введите имя новорожденной морской свинки: ");
Name = Console.ReadLine();
Console.WriteLine("Введите имена родителй морской свинки: ");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А саму логику создания и внесения родителей следует унести в конструктор класса


public string Pearent2 {get; set; }
}
} No newline at end of file
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type - тут будет определятся типом наследника, так что тоже не надо

}
}

public override string ToString()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Утаскиваю в родительский класс


public string Pearent2 {get; set; }
}
} No newline at end of file
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это позволяет заставить тех, кто реализует наследников поддреживать метод ToString - они просто обязаны будут реализовать GetInfo - который toString и вернет, в противном случае - никто не заставит их реализовать toString - и в какой то момент про это забудут

this.Vid = v;
}

public NewPet(string child, string v)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Название было плохое :(

--(')('),,)-(')('),,)---(')_(')---(..(')(')-(..(')(') ");
}

private void PetInfo(NewPet i, string name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это уже поддерживают сами pet - у них to string реализован

Krolik krosh = new Krolik();
Cavy cavy = new Cavy();
switch(go)
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот это максимально похоже а идею фабричного метода и его следует вынести отдельно, но пока для упрощения оставим как есть


break;
case "Sel":
Console.WriteLine("Введите кого вы хоите разводить: rabbit/cavy");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Было дублирование кода

case "Inf":
{
{
Console.Write("Введите имя животного о котором хотите унать: ");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это следует убрать - не дело меню про это знать

Spisok.Add(Name, new NewPet("rabbit"));
}

public override void NewPet()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это теперь делает базовый класс, только передавайте

Spisok.Add(Name, new NewPet("cavy"));
}

public override void NewPet()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опять же это теперь делает базовый класс, можно убирать

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants