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

75

我看到一些我正在维护的代码中两种方式都被使用了,但我不知道它们之间有什么区别。它们之间有区别吗?

补充一下,myCustomer是Customer类的一个实例。

7个回答

162

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

重要区别

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


39
我主要投票是为了修改。因为这是一个重要的区别。 - Benjamin Autin
如果VipCustomer继承自Customer类,那么如果在某个点上myCustomer = new VipCustomer(),其GetType()将与Customer类型不同。就像您所说的,运行时和编译时是两个非常不同的东西。 - LongChalk

27

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


19

如果您从Customer继承了一个类型,那么就会有区别。

class VipCustomer : Customer
{
  .....
}

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

5

首先,第一个需要一个实际的实例(例如 myCustomer),而第二个则不需要。


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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接