【发布时间】:2010-09-13 11:13:24
【问题描述】:
我已经在我维护的一些代码中看到了两者都完成了,但不知道有什么区别。有吗?
让我补充一点,myCustomer 是 Customer 的一个实例
【问题讨论】:
我已经在我维护的一些代码中看到了两者都完成了,但不知道有什么区别。有吗?
让我补充一点,myCustomer 是 Customer 的一个实例
【问题讨论】:
在您的情况下,两者的结果完全相同。它将是您从System.Type 派生的自定义类型。这里唯一真正的区别是当你想从你的类的实例中获取类型时,你使用GetType。如果您没有实例,但您知道类型名称(并且只需要实际的 System.Type 来检查或比较),则可以使用 typeof。
编辑:让我补充一点,对GetType 的调用在运行时得到解决,而typeof 在编译时得到解决。
【讨论】:
GetType() 用于在运行时查找对象引用的实际 类型。由于继承,这可能与引用对象的变量的类型不同。 typeof() 创建一个 Type 字面量,该字面量与指定的类型完全相同,并在编译时确定。
【讨论】:
是的,如果您从 Customer 继承类型,则会有所不同。
class VipCustomer : Customer
{
.....
}
static void Main()
{
Customer c = new VipCustomer();
c.GetType(); // returns typeof(VipCustomer)
}
【讨论】:
首先,您需要一个实际实例(即 myCustomer),其次您不需要
【讨论】:
typeof(foo) 在编译期间被转换为常量。 foo.GetType() 发生在运行时。
typeof(foo) 也直接转换为其类型的常量(即 foo),所以这样做会失败:
public class foo
{
}
public class bar : foo
{
}
bar myBar = new bar();
// Would fail, even though bar is a child of foo.
if (myBar.getType == typeof(foo))
// However this Would work
if (myBar is foo)
【讨论】:
typeof 在编译时执行,而 GetType 在运行时执行。这就是这两种方法的不同之处。这就是为什么在处理类型层次结构时,只需运行 GetType 即可找到类型的确切类型名称。
public Type WhoAreYou(Base base)
{
base.GetType();
}
【讨论】:
typeof 运算符将类型作为参数。它在编译时解决。 GetType 方法在对象上调用并在运行时解析。 第一种是在需要使用已知Type的时候使用,第二种是在不知道对象是什么的时候获取对象的类型。
class BaseClass
{ }
class DerivedClass : BaseClass
{ }
class FinalClass
{
static void RevealType(BaseClass baseCla)
{
Console.WriteLine(typeof(BaseClass)); // compile time
Console.WriteLine(baseCla.GetType()); // run time
}
static void Main(string[] str)
{
RevealType(new BaseClass());
Console.ReadLine();
}
}
// ********* By Praveen Kumar Srivastava
【讨论】: