【问题标题】:WCF Create generic property List<T> in DataMember classWCF 在 DataMember 类中创建通用属性 List<T>
【发布时间】:2020-01-14 14:24:31
【问题描述】:

我正在创建 WCF 服务,它有两个 OperationContract 返回 JSON 格式的记录列表

示例代码:

 List<Response> GetCollegeList()
 List<Response> GetStudentList(int CollegeId)
public class Colleges
{
    public int CollegeId { get; set; }
    public string CollegeName { get; set; }        
}
public class Students
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }

}
public class Response
{
    public string status_code { get; set; }
    public string responsemessage { get; set; }
    public List<College> data { get; set; }
}

我想为学生和学院创建通用列表

public List&lt;College&gt; data { get; set; }

如何为服务响应数据使用通用列表

public List<Response> GetCollegeList()
{
        List<Colleges> collegelist = new List<Colleges>();
        List<Response> response = new List<Response>();      
        dt =obj.GetCollegeList();

        if (dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                collegelist.Add(
                   new Colleges
                   {
                       CollegeId = Convert.ToInt32(row["CollegeId"].ToString()),
                       CollegeName = row["CollegeName"].ToString() 
                   }
                 );
            }
        }

        response.Add(new Response { status_code = "success", responsemessage = "College List", data = collegelist });


    return response;
}

【问题讨论】:

  • 我添加了answer,请查收。

标签: c# list wcf generics


【解决方案1】:

您应该将Response 设为通用:

public class Response<T>
{
    public string status_code { get; set; }
    public string responsemessage { get; set; }
    public T data { get; set; }
}

然后从GetCollegeList()返回Response&lt;List&lt;Colleges&gt;&gt;如下:

public Response<List<Colleges>> GetCollegeList()
{
    List<Colleges> collegelist = new List<Colleges>();

    dt =obj.GetCollegeList();

    if (dt.Rows.Count > 0)
    {
        foreach (DataRow row in dt.Rows)
        {
            collegelist.Add(
               new Colleges
               {
                   CollegeId = Convert.ToInt32(row["CollegeId"].ToString()),
                   CollegeName = row["CollegeName"].ToString() 
               }
             );
        }
    }
    Response<List<Colleges>> response = Response<List<Colleges>>()
    {
        status_code = "success", 
        responsemessage = "College List", 
        data = collegelist 
    };


    return response;
}

您也可以将此方法用于StudentsResponse&lt;List&lt;Students&gt;&gt;

【讨论】:

    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多