A
Andrus
I'm creating ComboBox class which uses entity list as datasource where
entity class name is passed as string. Entity list is filled dynamically at
run time.
So need to add entities of different types to corresponding entity lists.
I created general Add() method for this.
This method call causes exception from my code
"List does not have Add method"
How to fix ?
Andrus.
using System.Collections.Generic;
using System;
using System.Reflection;
class TestApplication {
static void Main() {
object customerList = Customer.GetEmptyList();
Add(customerList, new Customer());
}
// General routine to add entity to its corresponding list.
static void Add(object entityList, object entity) {
Type type = entityList.GetType();
Type[] types = new Type[1];
types[0] = entity.GetType();
MethodInfo methodInfo = type.GetMethod("Add",
BindingFlags.Public, null, types, null);
if (methodInfo == null)
// how to fix code so that this exception does not occur ?
throw new ApplicationException("List does not have Add method");
object[] parameters = new object[1];
parameters[0] = entity;
methodInfo.Invoke(entityList, parameters);
}
}
class Customer : ActiveRecordBase<Customer> {}
public class ActiveRecordBase<T> {
public static List<T> GetEmptyList() {
return new List<T>();
}
}
entity class name is passed as string. Entity list is filled dynamically at
run time.
So need to add entities of different types to corresponding entity lists.
I created general Add() method for this.
This method call causes exception from my code
"List does not have Add method"
How to fix ?
Andrus.
using System.Collections.Generic;
using System;
using System.Reflection;
class TestApplication {
static void Main() {
object customerList = Customer.GetEmptyList();
Add(customerList, new Customer());
}
// General routine to add entity to its corresponding list.
static void Add(object entityList, object entity) {
Type type = entityList.GetType();
Type[] types = new Type[1];
types[0] = entity.GetType();
MethodInfo methodInfo = type.GetMethod("Add",
BindingFlags.Public, null, types, null);
if (methodInfo == null)
// how to fix code so that this exception does not occur ?
throw new ApplicationException("List does not have Add method");
object[] parameters = new object[1];
parameters[0] = entity;
methodInfo.Invoke(entityList, parameters);
}
}
class Customer : ActiveRecordBase<Customer> {}
public class ActiveRecordBase<T> {
public static List<T> GetEmptyList() {
return new List<T>();
}
}