如何从Generic <t> List对象中提取数据

时间:2015-10-12 10:17:20

标签: c# .net generics foreach generic-list

我想创建泛型函数,我将只传递类名,并以通用类类型为基础从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("]");
 }

1 个答案:

答案 0 :(得分:-1)

我想创建泛型函数,我将只传递类名,并以通用类类型为基础从JSON对象获取CSV格式的数据(ID)。所有ID都将通过webservice并更新数据库。它的要求。

我想创建一个Generic函数,我希望将类名作为参数传递。因此,如果添加新类,将来我很容易使用该泛型函数。

现在工作正常..

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")
 }