1: private object GetList(object[] sourceArray, Type arrayType) {
2: Type listType = typeof(List<>).MakeGenericType(new System.Type[] { arrayType });
3: var list = Activator.CreateInstance(listType);
4: MethodInfo mi = listType.GetMethod("Add");
5: foreach (object item in sourceArray) {
6: mi.Invoke(list, new object[] { item });
7: }
8: return list;
9: }
What I did was to first create an instance of the List
Because we don't know what types and classes we are dealing with at Design Time, we can't just call Class.Method() to make things work. I first need to find the specific method I need. To do that I call System.Reflection.Type's GetMethod method. This comes out as a System.Reflection.MethodInfo type, thus the creation of the MethodInfo variable.
From here I simply iterate through the objects in the array passed in to the method, and Add them to the List
There is one small issue... The return is not exactly what you would expect. It is not a List
For instance, here is my calling method:
1: protected void butPeople_Click(object sender, EventArgs e) {
2: Type peopleType = typeof(People);
3: List<People> people = new List<People>();
4: people = GetList(GetPeople(), peopleType) as List<People>;
5: GridView1.DataSource = people;
6: GridView1.DataBind();
7: GridView1.Visible = true;
8: }
You can see in line 4 where I call the GetList method. I send it a custom type of People, along with an array of People. As I mentioned above, the return type of the GetList method is object, but this can be casted in to the type that we wanted it to be, as seen with the "as List
No comments:
Post a Comment