【问题标题】:What is the difference between typeof and the is keyword?typeof 和 is 关键字有什么区别?
【发布时间】:2011-10-14 09:06:36
【问题描述】:

两者之间的确切区别是什么?

// When calling this method with GetByType<MyClass>()

public bool GetByType<T>() {
    // this returns true:
    return typeof(T).Equals(typeof(MyClass));

    // this returns false:
    return typeof(T) is MyClass;
}

【问题讨论】:

  • 警告 - 如果您需要使用继承,这将不起作用。使用typeof(AClass).IsAssignableFrom(typeof(T)) 可以解决这个问题。见msdn.microsoft.com/en-us/library/…
  • @Will 感谢您提供的信息。在我的具体情况下无关紧要,但很高兴知道!

标签: c# generics types


【解决方案1】:

您应该在实例上使用is AClass,而不是比较类型:

var myInstance = new AClass();
var isit = myInstance is AClass; //true

is 也适用于基类和接口:

MemoryStream stream = new MemoryStream();

bool isStream = stream is Stream; //true
bool isIDispo = stream is IDisposable; //true

【讨论】:

  • 谢谢。很好,简短而全面的解释。
【解决方案2】:

is 关键字检查对象是否属于特定类型。 typeof(T)Type 类型,而不是 AClass 类型。

查看 MSDN 以获取 is keywordtypeof keyword

【讨论】:

  • 很遗憾我只能接受一个。至少我能做的就是投票给其他人。谢谢!
【解决方案3】:

typeof(T) 返回一个Type 实例。 Type 永远不等于 AClass

var t1 = typeof(AClass)); // t1 is a "Type" object

var t2 = new AClass(); // t2 is a "AClass" object

t2 is AClass; // true
t1 is AClass; // false, because of t1 is a "Type" instance, not a "AClass" instance

【讨论】:

  • 很遗憾我只能接受一个。至少我能做的就是投票给其他人。谢谢!
【解决方案4】:
  • typeof(T) 返回一个 Type 对象
  • Type 不是 AClass,而且永远不可能,因为 Type 不是从 AClass 派生的

你的第一句话是对的

【讨论】:

  • 很遗憾我只能接受一个。至少我能做的就是投票给其他人。谢谢!
【解决方案5】:

typeof 返回一个描述 TType 对象,该对象不是 AClass 类型,因此 is 返回 false。

【讨论】:

  • 很遗憾我只能接受一个。至少我能做的就是投票给其他人。谢谢!
【解决方案6】:
  • 首先比较两个 Type 对象(类型本身就是 .net 中的对象)
  • 其次,如果写得好(myObj 是 AClass)检查两种类型之间的兼容性。如果 myObj 是从 AClass 继承的类的实例,它将返回 true。

typeof(T) is AClass 返回 false,因为 typeof(T) 是 Type 并且 AClass 不继承自 Type

【讨论】:

  • 很遗憾我只能接受一个。至少我能做的就是投票给其他人。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 2019-04-05
  • 2014-05-26
  • 2015-07-28
相关资源
最近更新 更多