如何在以下情况下使用三元运算符? [英] How to use ternary operator in my following case?

查看:151
本文介绍了如何在以下情况下使用三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hii,





objEmployeeAbsence.SunWorkingHour = dtProperRecord.Rows [i] [SunWorkingHour]。ToString()== || dtProperRecord.Rows [i] [SunWorkingHour]。ToString()==0? null:上面代码中的Math.Round(float.Parse(dtProperRecord.Rows [i] [SunWorkingHour]。ToString()),2);



=> objEmployeeAbsence.SunWorkingHour中包含双数据类型。所以当我使用上面的类型条件时..如果它是真的,则不会设置null。如果我在那里使用0然后它取而不是空的





同时..如果我尝试使用if else块并尝试在objEmployeeAbsence.SunWorkingHour中指定null它被赋值..



这里是if else的代码



Hii ,


objEmployeeAbsence.SunWorkingHour = dtProperRecord.Rows[i]["SunWorkingHour"].ToString() == "" || dtProperRecord.Rows[i]["SunWorkingHour"].ToString() == "0" ? null : Math.Round(float.Parse(dtProperRecord.Rows[i]["SunWorkingHour"].ToString()), 2);

in the above code=> objEmployeeAbsence.SunWorkingHour has double datatype in it. so when i use above type condition .. null is not get set in it if its true. if i use 0 there then its taking but not the null


at the same time .. if i try to use if else block and try to assign null in objEmployeeAbsence.SunWorkingHour it gets assign ..

here is the code of if else

if (dtProperRecord.Rows[i]["SunWorkingHour"].ToString() == "" || dtProperRecord.Rows[i]["SunWorkingHour"].ToString() == "0")
                                        {
                                            objEmployeeAbsence.SunWorkingHour = null;
                                        }
                                        else
                                        {
                                            objEmployeeAbsence.SunWorkingHour = Math.Round(float.Parse(dtProperRecord.Rows[i]["SunWorkingHour"].ToString()), 2);
                                        }









我怎样才能做到这一点使用三元可能赋值null





how can i make this possible using ternary possible to assign null

推荐答案

Double是一个值类型(不是引用类型),因此在任何情况下都不能为它赋值。因为Match.Round返回一个double,所以整个三元表达式必须返回一个double,这意味着你不能使用null作为其中一个值。



相反,抛出null以及适当类型的objEmployeeAbsence.SunWorkingHour的双倍,无论声明为什么 - 它似乎有一个隐式转换可用,因此显式转换应该可以正常工作。
Double is a value type (not a reference type) so you cannot assign a null to it under any circumstances. Because Match.Round returns a double the whole ternary expression must return a double which means you can't use null as one of the values.

Instead, cast the null and the double to the appropriate type of objEmployeeAbsence.SunWorkingHour, whatever that is declared as - it appears there is an implicit conversion available, so an explicit cast should work fine.


这篇关于如何在以下情况下使用三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆