繁体   English   中英

在属性分配过程中使用typeof检查值的类型

[英]Using typeof to check type of value during property assignment

我正在创建一个具有用户可设置属性的基本类,该属性必须是int类型。 我该如何检查用户传递的类型实际上是整数,如果它是其他类型,则抛出异常?

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 但是我正在使用此SO问题中指定的类型检查。 我正在使用类型,因此检查将在编译时进行。

value是一个变量,因此typeof对它没有任何意义(如链接的问题所示)。

你需要:

set {
  Type t = value.GetType();
  if (t == typeof(int)) {
    _amount = value;
  } else {
    throw new ArgumentException("Amount must be an integer", "Amount");
  }
}

注意,这不会在编译时失败,因为setter直到执行才真正运行。 我不确定您要在此处阻止什么,如果将doublefloat传递给type系统,类型系统将执行正确的float 整个检查应该是不必要的。

好吧,除了该属性必须是整数之外,因为该属性被声明为整数!

您需要在值上使用.GetType()方法。 typeof是一个编译时操作。

所以

Type t = value.GetType();

但是,如果value为null,则会崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM