开发者

Why can't certain Silverlight objects be Nullable<> types?

开发者 https://www.devze.com 2023-01-13 20:01 出处:网络
Apparently you can\'t have a Nullable<Rectangle> in Silverlight. I\'d like to know the technical reasons why not and how many objects this may apply to?

Apparently you can't have a Nullable<Rectangle> in Silverlight. I'd like to know the technical reasons why not and how many objects this may apply to?

Today I accidentally started a small comment flamewar after stating that the "Rectangle" type was not a Nullable type. That is you can't have a "Nullable<Rectangle>" or a "Rectangle?"

My mistake was in testing it in Silverlight only and assuming that the behaviour of a Silverlight System.Windows.Shapes.Rectangle carried over to the System.Drawing.Rectangle type in .Net. Shame on me. I have since deleted my comments as they added no value to Stack Overflow.

If anyone can answer this quest开发者_如何学运维ion fully it would be much appreciated.


Nullable<T> can only be used with value types, or structs, and System.Windows.Shapes.Rectangle is a reference type, or class. You don't need to use Nullable<T>, since you can already assign a null reference to a variable of type System.Windows.Shapes.Rectangle:

System.Windows.Shapes.Rectangle rect = null;

By contrast, System.Drawing.Rectangle is a value type, so it cannot have a value of null. The default value is a rectangle of all zeros.

System.Drawing.Rectangle rect = null; // Does not compile
System.Drawing.Rectangle rect = 
    default(System.Drawing.Rectangle); // All fields are zero


A better answer would be to consider the differences between Option types and Nullable types, which is incidentally covered in the ECMA Standard for Common Language Infrastructure for Generics.

A great explanation of this has already been given for F# on StackOverflow.

So you don't want a Nullable<Rectangle>. You want an Option<Rectangle>.

See MSDN Documentation: Core.Option Module (F#)

0

精彩评论

暂无评论...
验证码 换一张
取 消