开发者

.NET Point.IsEmpty vs IsDefined

In my UI class, a developer has the option to define a location property (type of System.Drawing.Point). By default this property is initialized to Point.Empty. The internal code that is encapsulated by the class uses the .IsEmpty of the Point property to determine if a location has been set. If the property is not empty, the x/y value will be used. If empty, the code will attempt to place it with a row/column algorythm.

My Issue:

I am using the .IsEmpty of the property to determine if it was set. To my surprise, if a developer sets the property to 0,0 it came up as E开发者_如何学编程mpty. A point of 0,0 is valid in graphics. I also understand why the .IsEmpty returns true for the 0,0 value.

1) Without creating my own class or inheriting from System.Drawing.Point, is there a way to know if the property was set?

The only idea that I can think of is to default the property with a value of "new Point(-1,-1)" and test against that. Is there a better way? If not, please confirm.

I am using C# in Visual Studio 2005 and Visual Studio 2008

Thanks!


There's a few ways:

  1. Make the property a nullable Point, this way, it will be "null" when you haven't set it
  2. Track whether anything has called the setter method by setting a private Boolean field to true

ie. either:

public Point? Location { ... }

or:

public Point Location
{
    get ...
    set
    {
        _LocationSet = true;
        _Location = value;
    }
}


Keep the field as Point? (syntactic sugar for Nullable<Point>) instead of Point. That basically keeps track of whether the value is "real" one the null value. How you expose the property is up to you - you could expose it as Point and make it throw an exception if you try to fetch it without setting it, or you could expose it as Point? which would allow it to be "unset" by setting it to null again later.

Nullable value types are precisely designed for this sort of situation.


I might consider using a nullable Point: System.Drawing.Point? Nullable that would provide a cleaner path for knowing if something is set or not.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜