5

I'm having trouble converting a list object back to its original type without an explicit cast. My intention is to generalize methods so I could pass in different db Types such as Person or Company. I have no problem getting the values via reflection but I need to convert the actual list back to its original type List<typeT> instead of List<object> in the method I am passing it to. I am aware of the following methods:

 SomeList.ConvertAll(x => (typeT)x);
 SomeList.Cast<typeT>().ToList();

However for these methods I will have to explicitly cast typeT. I have tried the following:

formatted1.ConvertAll(x => Convert.ChangeType(x, typeT));

and

List<dynamic> newList = new List<dynamic>();
foreach (var p in SomeList)
{
   newList.Add(Convert.ChangeType(p, typeT);
}

No success thus far. Maybe I should have another game-plan for generalizing these methods altogether. right now I'm passing the lists in as follows:

public string returnJson(List<object> entity, string someString)
{
}

It seems like making returnJson generic would resolve most of these problems:

public string returnJson<T>(List<T> entity, string someString)
{
}

Now returnJson can be used generically, like:

returnJson<Company>(listOfCompanies, "someString");

and

returnJson<Person>(listOfPersons, "someOtherString");

You can still reflect over the objects, but the list is always a list of the type that you need at compile time. No casting required.

4

3 回答 3

6

似乎使returnJson泛型可以解决大多数这些问题:

public string returnJson<T>(List<T> entity, string someString)
{
}

现在returnJson可以泛型使用,例如:

returnJson<Company>(listOfCompanies, "someString");

returnJson<Person>(listOfPersons, "someOtherString");

您仍然可以反映对象,但列表始终是您在编译时需要的类型的列表。无需铸造。

于 2012-08-14T14:50:14.750 回答
1

Why not use generics, that way the calling function can do what it needs:

public string returnJson<T>(List<T> entity, string someString)
{
     //not sure what someString is for or why you need the type for this naming scheme

     JavaScriptSerializer jss = new JavaScriptSerializer();
     return jss.Serialize(entity);
}
于 2012-08-14T14:50:52.840 回答
0

You can use the dynamic keyword and reflection to create the list.

dynamic newList = Activator.CreateInstance(typeof(List<>).MakeGenericType(typeT));
foreach (var p in SomeList)
{
   newList.Add(p);
}
CallOtherMethodOverloadedForListOfPersonCompanyEtc(newList)
于 2012-08-14T18:08:11.793 回答