如何从Generic 对象列表
本文关键字:对象 列表 Generic | 更新日期: 2023-09-27 18:17:27
我想创建一个泛型函数,在这个泛型函数中,我将只传递类名,并根据泛型类类型从JSON对象中获取CSV格式的数据。
但是我不能在foreach循环时访问类成员。
public class Lifetouch
{
public int LifetouchID { get; set; }
public string Data { get; set; }
}
public class Lifetemp
{
public int LifetempID { get; set; }
public string Data { get; set; }
}
main()
{
getPerodicListofVitalSigns <Lifetouch>(new Lifetouch());
}
public static void getPerodicListofVitalSigns <T>( T clazz)
{
List<T> list_of_measurements_Original = JsonConvert.DeserializeObject<List<T>>(json_response);
// Got the list_of_measurements_Original count 2.
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var element in list_of_measurements_Original)
{
sb.Append(element.LifetouchID + ", ") // Not able to access the element of list LifetouchID
}
sb.Append("]");
}
我想创建一个泛型函数,在这个泛型函数中,我将传递类名并以基于泛型类类型的JSON对象的CSV格式获取数据(ID)。所有的id将通过webservice并更新数据库。这是必须的。
我想创建泛型函数,我想在其中传递类名作为参数。因此,如果添加了新类,将来我可以很容易地使用该泛型函数。
现在一切正常。
public class Lifetouch
{
public int LifetouchID { get; set; }
public string Data { get; set; }
}
public class Lifetemp
{
public int LifetempID { get; set; }
public string Data { get; set; }
}
main()
{
getPerodicListofVitalSigns <Lifetouch>(new Lifetouch());
getPerodicListofVitalSigns <Lifetemp>(new Lifetemp());
}
public static void getPerodicListofVitalSigns <T>( T clazz)
{
List<T> list_of_measurements_Original = JsonConvert.DeserializeObject<List<T>>(json_response);
// Got the list_of_measurements_Original count 2.
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var element in list_of_measurements_Original)
{
if (VitalSignName == "Lifetouch")
{
var vitalSign = element as Lifetouch;
dataString = dataString + (vitalSign.LifetouchID + ",");
}
else if (VitalSignName == "Lifetemp")
{
var vitalSign = element as Lifetemp;
dataString = dataString + (vitalSign.LifetempID + ",");
}
}
sb.Append("]");
string WebserviceAddress = "192..../json/reply/UpdateSyncStatus";
JSON_POST_Sender.ClassPost(WebserviceAddress, dataString), "true")
}