Perhaps a small question but im curious.
What is favored?
In a controllers action, when passing arguments, when and how should they be used?
public ActionResult Action(bool aBool = false)
or
public ActionResult Action(bool? aNullableBool)
I tend to use defualt-value as its a bit more clear and eassier to check, but am i thinking wrong?
The two are not equivalent. In the first example, the caller must specify true
or false
, if he does not, false
is used.
In the second line, the caller may provide true
, or false
, or null
. You will need to decide how to handle null
. That's a third value that you can get. Plus the caller can not omit it. He needs to pass a value.
The .HasValue
property of nullable variables can be quite handy sometimes. Having a nullable bool is like having a bool in a bool. Take Chuong Les example with the database, when you read a cell you may want to check that the cell actually holds a value before continuing (and ending up with an error further down the line).
Instead of having to make sure that isn't the case before reading the cell you can use a nullable variable and use if (aNullableBool.HasValue)
to make sure you have a value before continuing.
That beeing said, unless you run the risk of the variable getting the value null
you should use a default value.
我认为Route配置中的默认值是最好的。
It depends of the role of your bool.
If you want to have a default value or not (default behavior + just one other behavior), so just 2 behavior of this method.
If you want to have a third behavior as a default behavior, you will need to use a nullable bool.
So think about the needs of your method and choose accordingly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.