简体   繁体   中英

Will this code break?

A business object is returning a short? datatype.

How would I get this value into a variable?

short? myShort = SomeBusinessObject.UserBlah;

Is that correct? Will it break if it is null?

That's correct. You only have to worry if you're assigning myShort to a non-nullable short, in which case you have to check HasValue, like so:

short s = myShort.HasValue ? myShort.Value : (short) 0; // or some other short value

要将其放入变量中,请在检查myShort.HasValue之后使用myShort.Value

Are you actually trying to protect against SomeBusinessObject being null? If so, nullable types won't help you there. You still need to check whether your SomeBusinessObject is null.

I'm assuming that this is the case because if UserBlah returns a short then it'll never be null (as short is not a nullable type).

Don't forget about the null coalescing operator.

short myShort = SomeBusinessObject.UserBlah ?? 0;

if SomeBusinessObject.UserBlah is null, it just passes the value to the right of ?? so you can default it to something.

对,那是正确的。

myShort will be null if the business object returns null .

You can't reference myShort as a value type directly, so this is OK.

You can use myShort.HasValue to see if myShort is null or not.

Use myShort.Value to get the value. It will throw an exception if no value is defined.

You can use GetValueOrDefault() and pass in a default to get a value even if none is defined ( null ). This function returns the value you passed in if the nullable type is null .

myShort will only be null if UserBlah is implicitly convertible to Nullable<Int16> and it is set to null, in which case it will not break unless you try to access a member of myShort.Value .

You can also do this:

short defaultValue = 0;
short myShort      = SomeBusinessObject.UserBlah ?? defaultValue;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM