这是我的问题。我有一个基类和2个或多个派生类,我想编写一个通用方法来返回一个派生类,但是在检查传递的参数之前,我不知道它是什么类型。但是,我不能按照它说的那样List<Food>
传递给List<T>
中的GetData<T>
Cannot implicitly convert type 'System.Collections.Generic.List<Generic.Food>' to 'System.Collections.Generic.List<T>' Generic
解决方案1:错误
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; }
}
}
我知道我可以这样称呼: 解决方案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);
}
不要检查函数内部的参数。
但是,可以使用第一种解决方案吗?
谢谢。