[英]Constructor C# to return anonymous list
我有在传递匿名列表后需要匿名返回的列表,这里是代码。
public GenericResponseModel(bool success, string reason, List<dynamic> model)
{
Success = success;
Reason = reason;
model = model;
}
我如何返回匿名列表,因为之后我会有匿名模型。
public ResponseWrapper<GenericResponseModel> GetVehicleChecklist()
{
List<VehicleChecklist> VehicleCheckList = this.database.VehicleChecklists.Select(y => y).ToList();
if(VehicleCheckList != null)
{
IEnumerable<VehicleChecklistModel> mappedVehicleList = VehicleCheckList.MapVehicleCheckList();
return new GenericResponseModel(true, string.Empty, mappedVehicleList);
}}
我正在尝试从该代码中获取匿名列表。
听起来您正在尝试使用泛型<T>
来处理匿名类型的列表; 但是,构造函数不能是通用的,并且Model
属性需要反映T
。 为此,您需要使类型通用,并通过工厂方法代理它以使其可以使用(因为如果您不能说出名称,您就无法创建new
); 例子:
using System.Collections.Generic;
using System.Linq;
static class P
{
static void Main()
{
var list = new[]
{
new { Id = 1, Name = "abc"},
new { Id = 2, Name = "def"},
new { Id = 3, Name = "ghi"},
}.ToList();
var response = GenericResponseModel.Create(true, "because", list);
}
}
static class GenericResponseModel
{ // factory API to make it callable with an anonymous type
public static GenericResponseModel<T> Create<T>(bool success, string reason,
List<T> model) => new GenericResponseModel<T>(success, reason, model);
}
class GenericResponseModel<T>
{
public GenericResponseModel(bool success, string reason, List<T> model)
{
Success = success;
Reason = reason;
Model = model;
}
public bool Success { get; }
public string Reason { get; }
public List<T> Model { get; }
}
您还可以将公共属性下推:
abstract class GenericResponseModel
{
public bool Success { get; protected set; }
public string Reason { get; protected set; }
public static GenericResponseModel<T> Create<T>(bool success, string reason,
List<T> model) => new GenericResponseModel<T>(success, reason, model);
}
class GenericResponseModel<T> : GenericResponseModel
{
public GenericResponseModel(bool success, string reason, List<T> model)
{
Success = success;
Reason = reason;
Model = model;
}
public List<T> Model { get; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.