有人可以展示一个将 bool
属性映射到 enum
类型的例子吗?我担心定义中的 null
成员。
我需要这样的东西:
null
属性值到第一个枚举值;
0
到一秒;
1
到最后;
最佳答案
不幸的是,如这里所表达的AutoMapper null source value and custom type converter, fails to map?你不能直接将“null”映射到某个东西,因为 null 的映射将始终返回 default(T),所以你不能这样做:
CreateMap<bool?, MyStrangeEnum>()
.ConvertUsing(boolValue => boolValue == null
? MyStrangeEnum.NullValue
: boolValue.Value ? MyStrangeEnum.True : MyStrangeEnum.False);
另一方面,如果您映射一个对象属性,它将起作用:
public class MapperConfig : Profile
{
protected override void Configure()
{
CreateMap<Foo, Bar>()
.ForMember(dest => dest.TestValue,
e => e.MapFrom(source =>
source.TestValue == null
? MyStrangeEnum.NullValue
: source.TestValue.Value ? MyStrangeEnum.True : MyStrangeEnum.False));
}
}
public class Foo
{
public Foo()
{
TestValue = true;
}
public bool? TestValue { get; set; }
}
public class Bar
{
public MyStrangeEnum TestValue { get; set; }
}
public enum MyStrangeEnum
{
NullValue = -1,
False = 0,
True = 1
}
关于c# - 如何正确使用 automapper 将 bool 映射到枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36029096/