When developing my simple ORM, i need to replace POCOs by its proxies, so i code some methods to process list of POCOs with my ProxyBuilder to create proxy which extends POCO and implement IEntity then reassign POCO object with new proxy, but while doing this, i face a error when casting object after reassign item in List of POCOs, it say 'Unable to cast object of type 'Order' to type 'IEntity'
I simplify my code with some classes as followings:
public class Order
{
public string Code { get; set; }
public string Description { get; set; }
public DateTime Date { get; set; }
public decimal Total { get; set; }
}
interface IEntity
{
public long ID;
}
public class OrderProxy : Order, IEntity
{
// some functions of a proxy
}
Then consuming code like that
public void Run()
{
Order order1 = new Order() { .... };
Order order2 = new Order() { .... };
List<Order> orders = new List<Order>();
items.Add(order1);
items.Add(order2);
Process<Order>(orders);
// ERROR occured here 'Unable to cast object of type 'Order' to type 'IEntity'
((IEntity)order1).ID= 1;
}
public void Process<T>(List<T> items)
{
for (int i = 0; i < items.Count; i++)
{
items[i] = (T)CreateProxy();
}
}
private object CreateProxy(object obj)
{
// my ProxyBuilder will create new instance of OrderProxy depend on passed POCO parameter then return it
return new OrderProxy();
}
I've known that List<> with T is class, will passed by references but in this case i dont understand why it cant, the list variable orders after process include proxies as i want but order instance is still not proxy, may be i miss something? or anyone help me change the way process List<> in my code to get this, thank in advance