开发者

Best Way of Handling Value Types That Require an Auto value?

What is the best way to go about supporting an "auto" value for value types?

Let's say I wanted to float a texture 5 units off the right side of the screen. I wanted the end-developer to set the value like so:

mytexture.Margin.Right = 5;
mytexture.Margin.Left = int.Auto;

Internally, my 'layout manager' would need to know the end result of the positioning, but maintain that it is an automatic property for future comparisons and use.

So far I have been implementing this via a new value type that handles eve开发者_开发问答ry possible conversion under the sun but has an extra field to declare whether or not it represents an automatically set value or not.

Is this correct? Or is there a better way of handling this? My code currently ends up as:

mytexture.Margin.Right = 5;
mytexture.Margin.Left = Size.Auto;


You can also model this after the GridLength type available in WPF.

They basically made a struct, with a double value (amongst other things). They added implicit cast operators so it is easy to use from code:

RowDefinition row = new RowDefinition();
row.Height = 25; //Same as new GridLength(25);
row.Height = GridLength.Auto;

I'm sure they specifically check for the static member, GridLength.Auto underneath the hood to do the work.

MSDN for GridLength


It sounds very similar to Nullable<T>, in terms of having "any value, but also a flag saying whether or not a value is set". You could either use Nullable<T> directly, or if you felt that was a little bit of an abuse of the type, you could write your own similar type, e.g. Defaultable<T>.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜