[英]C#: What is this statement doing? dynObj.@switch == 1 ? true : false
I recently took over some code and came a across a statement that I wasn't sure what it was doing so I decided to post it.我最近接手了一些代码,遇到了一个我不确定它在做什么的声明,所以我决定发布它。
currCarbon.CleanGeneration = ( dynObj.@switch == 1? true: false); currCarbon.CleanGeneration = ( dynObj.@switch == 1?true: false);
Since 'dynObj' is a dynamic object holding a json value, is it checking if 'dynObj' contains a 'Switch' key / value?由于 'dynObj' 是一个动态 object 持有一个 json 值,它是否在检查 'dynObj' 是否包含一个 'Switch' 键/值?
Thanks for you help!谢谢你的帮助!
dynamic dynObj = GetValues();
if (dynObj != null) //json string from API
{
// Read the first record's carbon index
var prevCarbon = _dbContext.WatttimeApilog.OrderByDescending(c => c.CreatedDate).FirstOrDefault();
if (prevCarbon == null) //NO previous carbon value from database
{
//Plug in default values
currCarbon.Percentage = defaultPercent;
currCarbon.CleanGeneration = false;
currCarbon.Rating = defaultRating;
currCarbon.ValidUntil = DateTime.UtcNow;
insertFlag = true;
}
else
{
currCarbon.Percentage = dynObj.percent;
currCarbon.CleanGeneration = (dynObj.@switch == 1 ? true : false);
currCarbon.Rating = Convert.ToByte(dynObj.rating);
currCarbon.ValidUntil = dynObj.validUntil;
}
It's setting CleanGeneration
to true or false based on whether or not @switch
is equal to one via a ternary operator.它通过三元运算符根据
@switch
是否等于 1 将CleanGeneration
设置为 true 或 false。
EDIT: The code isn't the most clean and can be shortened to just currCarbon.CleanGeneration = dynObj.@switch == 1;
编辑:代码不是最干净的,可以缩短为
currCarbon.CleanGeneration = dynObj.@switch == 1;
Linked is docs on the ternary operator: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator链接的是关于三元运算符的文档: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.