gpt4 book ai didi

c# - Automapper "IsNull"目标后缀无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-03 22:39:17 25 4
gpt4 key购买 nike

我有以下代码:

  class Program
{
static void Main(string[] args)
{
var srcClass = new SourceClass { Value1 = null, Value2 = 10, Value3 = 20 };
Mapper.Initialize(cfg =>
{
cfg.RecognizeDestinationPostfixes("IsNull");
cfg.CreateMap<SourceClass, TargetClass>();
});
var targetClass = Mapper.Map<SourceClass, TargetClass>(srcClass);

}
}
public class SourceClass
{
public int? Value1 { get; set; }
public int? Value2 { get; set; }
public int? Value3 { get; set; }
}
public class TargetClass
{
public bool Value1IsNull{ get; set; }
public bool Value2IsNull { get; set; }
public bool Value3IsNull { get; set; }
}

我希望 targetClass 实例具有以下值:true、false、false;但我收到相反的结果:false,true,true。

如何解决这个问题?

最佳答案

这是因为当我们将整数转换为 bool 值时,它为 null 返回 false,为值返回 true。

            int? a;
a = null;
//Convert null to boolean
bool a1 = Convert.ToBoolean(a);
Console.WriteLine("Null Value - " + a1);
a = 1;
//Convert integer value to boolean
a1 = Convert.ToBoolean(a);
Console.WriteLine("Have Value - " + a1);
var srcClass = new SourceClass { Value1 = null, Value2 = 1, Value3 = 20 };
Mapper.Initialize(cfg =>
{
cfg.RecognizeDestinationPostfixes("IsNull");
cfg.CreateMap<SourceClass, TargetClass>();
});
var targetClass = Mapper.Map<SourceClass, TargetClass>(srcClass);
Console.WriteLine(targetClass.Value1IsNull+" - " +targetClass.Value2IsNull+" - " +targetClass.Value3IsNull);

输出:

Null Value - False
Have Value - True
False - True - True

关于c# - Automapper "IsNull"目标后缀无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53226945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com