Это звучит , как будто вы пытаетесь использовать обобщенный c <T>
для обработки списка анонимного типа; однако конструктор не может быть обобщенным c, а свойство Model
должно отражать T
. Для этого вам нужно сделать тип generi c и прокси к нему через фабричный метод, чтобы сделать возможным использование (поскольку вы не можете 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; }
}
Вы можете также указать sh общие свойства:
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; }
}