何时何地使用GetType()或typeof()? [英] When and where to use GetType() or typeof()?
问题描述
这为什么起作用
if (mycontrol.GetType() == typeof(TextBox))
{}
这不是吗?
Type tp = typeof(mycontrol);
但这可行
Type tp = mycontrol.GetType();
我自己使用 is
运算符检查类型但是当我使用 typeof()
和 GetType()
I myself use is
operator for checking type but my understanding fails when I use typeof()
and GetType()
何时何地使用 GetType()
或 typeof()
?
推荐答案
typeof
是一个运算符,用于获取在 compile-time 时已知的类型(或至少一个泛型类型参数)。 typeof
的操作数始终是类型或类型参数的名称-从不带值的表达式(例如变量)。有关更多详细信息,请参见 C#语言规范。
typeof
is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof
is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.
GetType()
是您在单个对象上调用的一种方法,用于获取对象的执行时间类型。
请注意,除非您仅 要确切地想要 TextBox
的实例(而不是子类的实例),否则通常使用: / p>
Note that unless you only want exactly instances of TextBox
(rather than instances of subclasses) you'd usually use:
if (myControl is TextBox)
{
// Whatever
}
或
TextBox tb = myControl as TextBox;
if (tb != null)
{
// Use tb
}
这篇关于何时何地使用GetType()或typeof()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!