无法将dto列表转换为动态列表

  • 本文关键字:列表 转换 动态 dto c#
  • 更新时间 :
  • 英文 :


如何使其工作?它给我一个错误不能implicitly convert。我的WebApp上有很多DTO,我需要一个占位符变量。

注意:这不是我的WebApp上的实际代码,这只是我想做什么的想法。

public class DTO1
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DTO2
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DTO1Service
{
public static List<DTO1> GetListOfDTO1()
{
return new List<DTO1>
{
new DTO1 { Id = 1, Name = "DTO 1" },
new DTO1 { Id = 2, Name = "DTO 2" }
};
}
}
public class DTO2Service
{
public static List<DTO2> GetListOfDTO2()
{
return new List<DTO2>
{
new DTO2 { Id = 1, Name = "DTO 1" },
new DTO2 { Id = 2, Name = "DTO 2" }
};
}
}
public class Program
{
public static void Main(string[] args)
{
var entities = new List<dynamic>();
var serviceType = Console.ReadLine();
if(serviceType == "1")
entities = (dynamic)DTO1Service.GetListOfDTO1();
else if (serviceType == "2")
entities = (dynamic)DTO2Service.GetListOfDTO2();
Console.ReadLine();
}
}

您可以使用Cast方法将其显式强制转换为dynamic,如下所示:

if(serviceType == "1")
entities = DTO1Service.GetListOfDTO1().Cast<dynamic>().ToList();
else if (serviceType == "2")
entities = DTO2Service.GetListOfDTO2().Cast<dynamic>().ToList();

你选错了。您正试图将dynamic分配给List<dynamic>,而不是列表成员

您可以创建一个新实例并在中传递值

if(serviceType == "1")
entities = new List<dynamic>(DTO1Service.GetListOfDTO1());
else if (serviceType == "2")
entities = new List<dynamic>(DTO2Service.GetListOfDTO2());

或者只填充最初创建的实例

if(serviceType == "1")
entities.AddRange(DTO1Service.GetListOfDTO1());
else if (serviceType == "2")
entities.AddRange(DTO2Service.GetListOfDTO2());

我个人更喜欢第二个选项,因为您已经初始化了变量,只需要填充它,而不是创建一个实例来重新分配它。

根据对这个问题的评论,我认为OP需要这样的东西:

public interface IAmDTO {
int Id { get; set; }
string Name { get; set; }
}
public class DTO1 : IAmDTO {
public int Id { get; set; }
public string Name { get; set; }
}
public class DTO2 : IAmDTO {
public int Id { get; set; }
public string Name { get; set; }
}
public class DTO1Service {
public static List<DTO1> GetListOfDTO1() =>
new List<DTO1>
{
new DTO1 { Id = 1, Name = "DTO 1" },
new DTO1 { Id = 2, Name = "DTO 2" },
};
}
public class DTO2Service {
public static List<DTO2> GetListOfDTO2() =>
new List<DTO2>
{
new DTO2 { Id = 1, Name = "DTO 1" },
new DTO2 { Id = 2, Name = "DTO 2" },
};
}
}
public static class DTOExtensions {
public static void DtoHelper(this IEnumerable<IAmDTO> dtoS) {
foreach(var dto in dtoS) {
//DO SOMETHING WITH
var id = dto.Id;
var name = dto.Name;
}
}

}

最新更新