【发布时间】:2019-03-26 12:06:56
【问题描述】:
如何将一个对象列表中的所有内容复制到另一个对象列表中。两个对象的结构相同,但名称不同。
代码如下:
class Program
{
static void Main(string[] args)
{
List<Test> lstTest = new List<Test>();
List<Test2> lstTest2 = new List<Test2>();
lstTest.Add(new Test { Name = "j", Score = 2 });
lstTest.Add(new Test { Name = "p", Score = 3 });
lstTest2 = lstTest.ConvertAll(x => (Test)x);
}
}
class Test
{
private string name;
private int score;
public string Name
{
get { return name; }
set { this.name = value; }
}
public int Score
{
get { return score; }
set { this.score = value; }
}
}
class Test2
{
private string name;
private int score;
public string Name
{
get { return name; }
set { this.name = value; }
}
public int Score
{
get { return score; }
set { this.score = value; }
}
}
我得到的错误是
不能隐式转换类型
System.Collections.Generic.List<Test>给System.Collections.Generic.List<cTest2>
【问题讨论】:
-
Automapper 是很好的解决方案,但我不允许使用它:(
-
这两个类是相同的,在现实世界的场景中,一个通用的基类或接口将是最好的方法,imo
-
@Josef 没有魔术棒,您要么手动完成,要么使用一些自动映射工具完成。并且根据您当前提供的示例,它应该很容易,但是如果您说您有复杂的东西并且无法使用它,那么您对解决方案的期望是什么?
标签: c# generic-list