C#中的myCustomer.GetType()和typeof(Customer)有什么区别?


74

我已经在维护的某些代码中看到了两者,但是不知道它们之间的区别。有一个吗?

让我补充一点,myCustomer是Customer的实例

Answers:


159

两种情况下的结果在您的情况下完全相同。从派生的是您的自定义类型System.Type。唯一真正的区别是,当您要从类的实例获取类型时,可以使用GetType。如果您没有实例,但是知道类型名称(只需要System.Type检查或比较实际的名称),则可以使用typeof

重要区别

编辑:让我补充一点,对调用的GetType获取在运行时解决,而typeof在编译时解决。


38
我主要是为编辑投票。因为那是重要的区别。
本杰明·奥丁

不一定完全相同。假设VipCustomer继承自Customer,那么如果某个时候myCustomer = new VipCustomer(); 那么它的GetType()将不同于Customer类型。如您所说,运行时和编译时是两个非常不同的事物。
LongChalk

27

GetType()用于在运行时查找对象引用的实际类型。由于继承,这可能不同于引用对象的变量的类型。typeof()创建一个Type文字,该文字与指定的确切类型相同,并在编译时确定。


20

是的,如果您有从Customer继承的类型,则有所不同。

class VipCustomer : Customer
{
  .....
}

static void Main()
{
   Customer c = new VipCustomer();
   c.GetType(); // returns typeof(VipCustomer)
}


5

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)

2

typeof在编译时执行,而GetType在运行时执行。这就是这两种方法的不同之处。这就是为什么在处理类型层次结构时,只需运行GetType即可找出类型的确切类型名称。

public Type WhoAreYou(Base base)
{
   base.GetType();
}

1

typeof运算符将类型作为参数。它在编译时解决。GetType方法在对象上调用,并在运行时解析。第一种用于需要使用已知类型的类型,第二种用于在不知道对象类型的情况下获取对象的类型。

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 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.