我想将抽象类型的任意列表映射到共享相同基类型的任意一组属性。 这里是一些UnitTest代码,它目前失败了,我想成功。你能帮助我,得到一个通用的解决方案吗?Automapper:成员列表
这里是类:
public class Source
{
public string Name { get; set; } = "SomeName";
public Dictionary<string, ValueType> SourceList { get; set; } = new Dictionary<string, ValueType>();
}
public interface IDestination
{
string Name { get; set; }
}
public class Destination : IDestination //And many other classes like this, with other properties inherited from ValueType
{
public string Name { get; set; }
public double DoubleValue { get; set; }
public int IntValue { get; set; }
public string SomeOtherProperty { get; set; }
}
,这里是单元测试,我想成功:
[TestMethod]
public void TestMethod1()
{
var source = new Source();
source.SourceList.Add("IntValue", (int) 3);
source.SourceList.Add("DoubleValue", (double) 3.14);
Mapper.Initialize(config =>
{
//Put in some magic code here!!!
});
var destinationAbstract = Mapper.Map<Source, IDestination>(source); //the type of destination is known only at runtime. Therefore Mapping to Interface
var destination = (Destination) destinationAbstract;
Assert.AreEqual(source.Name, destination.Name);
Assert.AreEqual((int)source.SourceList["IntValue"], destination.IntValue);
Assert.AreEqual((double)source.SourceList["DoubleValue"], destination.DoubleValue);
}
请注意,这
- 数的类,继承自IDestination仅在运行时已知
- 在SOURCELIST的内容可以为每个源实例是不同的,因此目标类的属性,也可以改变每一个类定义
我希望你能帮助我,因为我无法确定通用解决方案在文档的帮助下。
在此先感谢。
感谢您的回答。据我所知,这种映射只适用于源类型Dictionary,没有其他Dictionary类型。如果我是对的,这对我的Dictionary 有什么帮助? (注意:ValueType只是任何自定义基类型的一个示例) –
Hardy
我尝试使用Dictionary的映射,但存在两个问题:1.)我的源类型是Dictionary 和我不想投反对票。和2.)我的目标类型也包含其他成员,这些成员不是从源词典中读取的。 –
Hardy
为什么不呢?关于第二点,源词典中具有匹配目标属性的所有条目都将被映射,所以我不确定你的意思。 –