The code below produces this output fine:
This is page one.
This is page two.
But how do I change it so that the PageItem objects are instantiated dynamically from the List<string>
?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestInstant
{
class Program
{
static void Main(string[] args)
{
List<string> pageItemsIdCodes = new List<string>() { "PageItem1", "PageItem2" };
PageItemManager pageItemManager = new PageItemManager(pageItemsIdCodes);
pageItemManager.DisplayMenu();
Console.ReadLine();
}
}
class PageItemManager
{
private Dictionary<string, BasePageItem> PageItemRecords = new Dictionary<string, BasePageItem>();
public PageItemManager(List<string> pageItemsIdCodes)
{
//manually
PageItemRecords.Add("PageItem1", new PageItem1(this));
PageItemRecords.Add("PageItem2", new PageItem2(this));
//HOW DO i DO THIS DYNAMICALLY:
//PSEUDO-CODE:
//foreach (string pageItemIdCode in pageItemsIdCodes)
//{
// Type t = Type.GetType(pageItemIdCode);
// //ERROR: Cannot implicitly convert type 'TestInstant.PageItemManager' to 'TestInstant.BasePageItem'
// BasePageItem pageItem = Activator.CreateInstance(t, new BasePageItem[] { this });
// PageItemRecords.Add(pageItemIdCode, pageItem);
//}
//Type t = Type.GetType(pageItemIdCode);
//ERROR: Cannot implicitly convert type 'object' to 'TestInstant.BasePageItem'.
//BasePageItem pageItem = Activator.CreateInstance(t); // Change constructor
//pageItem.PageItemManager = this; // Add SetMananger call to BasePageItem
//PageItemRecords.Add(pageItemIdCode, pageItem);
}
public void DisplayMenu()
{
foreach (var pageItemRecord in PageItemRecords)
{
Console.WriteLine(pageItemRecord.Value.Title);
}
}
}
class BasePageItem
{
public string Title { get; set; }
protected PageItemManager pageItemManager;
public BasePageItem(PageItemManager pageItemManager)
{
this.pageItemManager = pageItemManager;
}
}
class PageItem1 : BasePageItem
{
public PageItem1(PageItemManager pageItemManager)
: base(pageItemManager)
{
Title = "This is page one.";
}
}
class PageItem2 : BasePageItem
{
public PageItem2(PageItemManager pageItemManager)
: base(pageItemManager)
{
Title = "This is page two.";
}
}
}