日期:2014-05-18 浏览次数:20849 次
class Program { static void Main(string[] args) { ScreenPosition sp = new ScreenPosition(100,23); //sp.X = -100; //sp.Y = 23; //sp.SetX(100); //Console.WriteLine(sp.GetX()); //sp.X = 100; } } struct ScreenPosition { private int x; private int y; public ScreenPosition(int x, int y) { this.x = rangeCheckedX(x); this.y = rangeCheckedY(y); } private static int rangeCheckedX(int x) { if (x < 0 || x > 1280) { throw new ArgumentOutOfRangeException("X"); } return x; } private static int rangeCheckedY(int y) { if (y < 0 || y > 1024) { throw new ArgumentOutOfRangeException("Y"); } return y; } } }
public ScreenPosition(int x, int y) { this.x = x; //这里是关键 this.y = y; //这里是关键 this.x = this.rangeCheckedX(x); this.y = this.rangeCheckedY(y); } private int rangeCheckedX(int x) { if (x < 0 || x > 1280) { throw new ArgumentOutOfRangeException("X"); } return x; } private int rangeCheckedY(int y) { if (y < 0 || y > 1024) { throw new ArgumentOutOfRangeException("Y"); } return y; }
------解决方案--------------------
其实这样可能美一点
this.x = 0; this.y = 0; this.x = this.rangeCheckedX(x); this.y = this.rangeCheckedY(y);