Here is my problem. I have one base class and 2 or more derived class, I want to write a generic method to return one derived class but I don't know what type it is until it checked the passed paramater. However, I can't pass List<Food>
to List<T>
in GetData<T>
as it said
Cannot implicitly convert type 'System.Collections.Generic.List<Generic.Food>' to 'System.Collections.Generic.List<T>' Generic
Solution 1: Error
namespace Generic
{
class Program
{
static void Main(string[] args)
{
string s = "some json document string here";
var p = GetData<Cargo>(0, s);
}
static List<T> GetData<T>(int type, string src) where T : Cargo
{
if (type == 0)
return JsonConvert.DeserializeObject<List<Food>>(src);
else
return JsonConvert.DeserializeObject<List<Paper>>(src);
}
}
public abstract class Cargo
{
public double Price { get; set; }
}
public class Food : Cargo
{
public double Calorie { get; set; }
}
public class Paper : Cargo
{
public int Height { get; set; }
public int Width { get; set; }
}
}
I know I could call something like this: Solutioon 2
static void Main(string[] args)
{
string s = "some json document string here";
int type = 0;
if (type == 0)
GetData<Food>(s);
else
GetData<Paper>(s);
}
static List<T> GetData<T>(string src) where T : Cargo
{
return JsonConvert.DeserializeObject<List<T>>(src);
}
and don't check the parameter inside the function.
However, is there any possible to use the first solution?
Thanks.