nei*_*ldt 4 c# function object
我有10个不同的类,但下面是两个用于此问题的目的:
public class Car
{
public int CarId {get;set;}
public string Name {get;set;}
}
public class Lorry
{
public int LorryId {get;set;}
public string Name {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个像这样的功能
public static object MyFunction(object oObject, string sJson)
{
//do something with the object like below
List<oObject> oTempObject= new List<oObject>();
oTempObject = JsonConvert.DeserializeObject<List<oObject>>(sJson);
return oTempObject;
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是将我创建的对象(如下面的oCar)传递给函数.
Car oCar = new Car();
Run Code Online (Sandbox Code Playgroud)
我的问题是如何将不同类型的对象传递给同一个函数?
使用泛型方法将解决诀窍:
public static List<T> MyFunction<T>(string sJson)
{
//do something with the object like below
return (List<T>)JsonConvert.DeserializeObject<List<T>>(sJson);
}
Run Code Online (Sandbox Code Playgroud)
用法:
List<Car> cars = MyFunction<Car>(sJson);
Run Code Online (Sandbox Code Playgroud)
要么
List<Lorry> cars = MyFunction<Lorry>(sJson);
Run Code Online (Sandbox Code Playgroud)
更新(感谢Matthew注意方法名称背后的类型),顺便说一句:当参数为T时,不需要这样做.