<分区>
为什么会这样
if (mycontrol.GetType() == typeof(TextBox))
{}
这不是吗?
Type tp = typeof(mycontrol);
但这行得通
Type tp = mycontrol.GetType();
我自己使用 is
运算符来检查类型,但是当我使用 typeof()
和 GetType()
时我的理解失败了
何时何地使用 GetType()
或 typeof()
?
<分区>
为什么会这样
if (mycontrol.GetType() == typeof(TextBox))
{}
这不是吗?
Type tp = typeof(mycontrol);
但这行得通
Type tp = mycontrol.GetType();
我自己使用 is
运算符来检查类型,但是当我使用 typeof()
和 GetType()
时我的理解失败了
何时何地使用 GetType()
或 typeof()
?
最佳答案
typeof
是一个运算符,用于获取在编译时 已知的类型(或至少是泛型类型参数)。 typeof
的操作数始终是类型或类型参数的名称 - 从不 是具有值的表达式(例如变量)。查看C# language specification了解更多详情。
GetType()
是您调用单个对象的方法,以获取对象的执行时间类型。
请注意,除非您只想要 TextBox
的实例(而不是子类的实例),否则您通常会使用:
if (myControl is TextBox)
{
// Whatever
}
或者
TextBox tb = myControl as TextBox;
if (tb != null)
{
// Use tb
}
关于c# - 何时何地使用 GetType() 或 typeof()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11312111/