Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Full Tutorial on indiedevart.wordpress.com
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication108
- {
- public interface IInventory
- {
- string Name { get; set; }
- void PrintName();
- }
- public class Backpack : IInventory, IEnumerable<IInventory>
- {
- private List<IInventory> _subordinates = new List<IInventory>();
- public string Name { get; set; }
- public void AddSubordinate(IInventory subordinate)
- {
- _subordinates.Add(subordinate);
- }
- public void RemoveSubordinate(IInventory subordinate)
- {
- _subordinates.Remove(subordinate);
- }
- public IInventory GetSubordinate(int index)
- {
- return _subordinates[index];
- }
- public void PrintName()
- {
- Console.WriteLine(Name);
- }
- public IEnumerator<IInventory> GetEnumerator()
- {
- foreach (IInventory subordinate in _subordinates)
- {
- yield return subordinate;
- }
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
- public class Item : IInventory
- {
- public string Name { get; set; }
- public void PrintName()
- {
- Console.WriteLine(Name);
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Backpack inventory= new Backpack{ Name = "Inventory" };
- Backpack backpack = new Backpack { Name = "Backpack" };
- inventory.AddSubordinate(backpack);
- inventory.AddSubordinate(new Item { Name = "Sword" });
- inventory.AddSubordinate(new Item { Name = "Armor" });
- backpack.AddSubordinate(new Item { Name = "Shield" });
- Console.WriteLine("List of items in inventory");
- foreach (IInventory element in inventory)
- {
- element.PrintName();
- }
- Console.ReadKey();
- }
- }
- }
Add Comment
Please, Sign In to add comment