我正在尝试比较不同的rest api json响应的返回值,我想创建一个方法,将类名作为paremeter,如下所示。我尝试过提交string和typeof()。想知道将ClassName作为参数传递的正确方法是什么,或者我应采取不同的方法。
class Employee
{
//different properties
}
class Patient
{
//different properties
}
class Tests
{
public bool compareValues(ClassName)
{
string expectedValues = File.ReadAllText(filePath);
var expectedValues = JsonConvert.DeserializeObject<ClassName[]>(fileResult, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
//similar thing: call rest api as above.
//compare logic
}
}
感谢您的帮助!
答案 0 :(得分:1)
它被称为泛型。见下面的例子:
public bool compareValues<T>(ClassName)
{
string expectedValues = File.ReadAllText(filePath);
var expectedValues = JsonConvert.DeserializeObject<T[]>(fileResult, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
//similar thing: call rest api as above.
//compare logic
}
var employeeResult = compareValues<Employee>();
var patientResult = compareValues<Patient>();
注意方法签名已更改,它包含<T>
- 类名占位符。如果您已经知道方法中使用了哪些类,这将有效。如果只有类名作为字符串,则必须反序列化json而不指定具体的类JsonConvert.DeserializeObject(jsonString)
并使用JObject
(参见Json.Net文档)