我有课
public class A
{
public string SomeProperty{ get; set; }
public string URI { get; set; }
}
和另一个类
public class B
{
public string SomeProperty { get; set; }
public Uri URI { get; set; }
}
我打算使用 AutoMapper 从 A 的对象创建 B 的对象,但由于 URI 的数据类型不同,我确实需要编写一些代码。 我能够通过写作实现我想要的目标
cfg.CreateMap<A, B>()
.AfterMap((src, targ) =>
{
Uri uri;
Uri.TryCreate(src.URI, UriKind.Absolute, out uri);
targ.URI = uri;
});
想知道这是否是最好的方法?
最佳答案
您的解决方案工作正常,但您可以使用 ITypeConverter
创建字符串和 URI 的映射:
public class StringToUriConverter : ITypeConverter<string, Uri>
{
public Uri Convert(string source, Uri destination, ResolutionContext context)
{
Uri.TryCreate(source, UriKind.Absolute, out destination);
return destination;
}
}
Depending on the situation, if you were mapping to an existing object, you would have to use the
destination
parameter and just update it, although this doesn't make much sense forUri
specifically.
然后你只需像这样映射你的类:
Mapper.Initialize(cfg => {
cfg.CreateMap<string, Uri>().ConvertUsing<StringToUriConverter>();
cfg.CreateMap<A, B>();
});
Mapper.AssertConfigurationIsValid();
这里的想法是,如果您有任何其他映射需要将字符串转换为 Uri,AutoMapper 现在已经知道如何执行此操作,您不需要显式使用 .ForMember
,也不再是 .AfterMap
了。
关于c# - AutoMapper 将具有字符串属性的对象转换为具有 URI 属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48640305/