次のスキームは、文字列/プリミティブをうまく処理します。ただし、リストを処理する場合、getObj()で型キャストエラーが発生します。使用されるタイプは動的であり、この一般的な使用が必要です。それを達成するためのより良い方法はありますか?
public static Object obj;
static public T getObj<T>()
{
return (T)obj;
}
private static string getStr()
{
return "some string";
}
private static List<Object> getList()
{
List<Object> res = new List<object>();
Object o = "str1";
res.Add(o);
o = "str2";
res.Add(o);
return res;
}
public static void Main()
{
obj = getStr();
string s = getObj<string>();
obj = getList();
List<string> slist = getObj<List<string>>();
}