我正在创建一个基本类,该类具有用户可设置属性,该属性必须是int
类型。我该如何去检查用户传入的类型实际上是一个整数,并且如果它是某种其他类型则抛出异常?在属性赋值期间使用typeof检查值的类型
class MyClass
{
private int _amount;
public int Amount
{
get
{
return _amount;
}
set
{
Type t = typeof(value);
if(t == typeof(int))
{
_amount = value;
}
else
{
throw new ArgumentException("Amount must be an integer", "Amount");
}
}
}
}
Visual Studio IDE说The type or namespace value could not be found
。但我正在使用类型检查in this SO question。我正在使用类型,因此检查将在编译时发生。
你尝试写的代码在这个例子中毫无意义:因为你声明的属性类型为'INT ','value'是* int *所必需的。由于'int'是一个'struct',它不能是某种不兼容的子类型或空值,它必须是一个可用的'int'。 –