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)
{
}

Just to add a little more to nico's response to make it more useful for generic copy and paste use by saving the time of typing in individual cachefile names for each file saved.

Original:

$cachefile = 'cache/index-cached.html';

Modified:

$cachefile = $_SERVER['DOCUMENT_ROOT'].'/cache/'.pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_FILENAME).'-cached.html';

What this does is to take the filename of whatever file it is located in, minus the extension (.php in my case), and appends the "-cached.html" label and new extension to the cached file. There are probably more efficient ways of doing this, but it works for me and hopefully save others some time and effort.

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

ジェネリックを使用しないのはなぜですか。そうすれば、呼び出し元の関数が必要なことを実行できます。

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

dynamic キーワードとリフレクションを使用してリストを作成できます。

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