我有类Pos:
public class Pos
{
int x;
int y;
public int X
{
get
{
return x;
}
set
{
try
{
if (value == 3)
{
x = value;
}
}
catch
{
throw new ArgumentException();
}
}
}
public int Y { get; set; }
public Pos(int x, int y)
{
X = x;
Y = y;
}
}
我创建了一个实例,X = 0。也就是说,据我所知,在 value = 3 -> x = 0 和构造函数 X = 0 的情况下,然后创建一个类的实例。当 x 属性设置器失败时,如何防止创建类的实例?我将创建一个不应包含“错误”对象的列表。
我很难理解这段代码应该做什么以及问题与它有什么关系,但我想也许你在问“我如何验证属性设置器参数的正确性?”
遵循这个模式:
// Class names should be words, not abbrvtns like "Pos"
public class Position
{
private int x;
private bool IsValidX(int possibleX)
{
// Here return true if possibleX is valid, false otherwise
}
public int X
{
get { return this.x; }
set
{
if (!IsValidX(value))
throw new ArgumentException("explanation here", "value");
this.x = value;
}
}
// Now do the same thing for Y.
public Position(int x, int y)
{
if (!IsValidX(x))
throw new ArgumentException("explanation here", "x");
if (!IsValidY(y))
throw new ArgumentException("explanation here", "y");
this.x = x;
this.y = y;
}
}
请注意,我们想要抛出不同的参数异常,因为每种情况下的参数名称都不同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句