【问题标题】:Check if an object is a type or a subtype [duplicate]检查对象是类型还是子类型[重复]
【发布时间】:2020-12-21 05:49:57
【问题描述】:

考虑以下检查对象是否属于特定类型的代码:

public MyMethod(object myObject)
{
    if (myObject.GetType() != typeof(MyClass))
    {
        throw new ArgumentException("The type is not MyClass");
    }
}

如何检查myObject 的类型,以便它允许MyClass子类型

【问题讨论】:

  • 它似乎工作,但是有一个警告:The given expression is never of the provided ('MyClass') type

标签: c# object inheritance types


【解决方案1】:

只需使用is 运算符。

if (!(myObject is MyClass))

如果可能,限制参数类型,以便编译器为您强制执行该规则;

public MyMethod(MyClass myObject)

【讨论】:

  • 是的,这更有意义+1
  • 按需要工作
猜你喜欢
  • 2011-02-14
  • 2013-07-14
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2011-09-26
  • 2016-12-31
  • 2016-11-24
  • 2020-04-27
相关资源
最近更新 更多