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

use*_*931 73 .net c#

我已经看到我在维护的一些代码中完成了两个,但不知道区别.有吗?

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

Kil*_*fer 158

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

重要的区别

编辑:让我补充说,调用GetType在运行时得到解决,而typeof在编译时解析.

  • 我投票主要是为了编辑.因为那是一个重要的区别. (36认同)

Jef*_*dge 27

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


Jak*_*urc 20

是的,如果您有来自Customer的继承类型,则会有所不同.

class VipCustomer : Customer
{
  .....
}

static void Main()
{
   Customer c = new VipCustomer();
   c.GetType(); // returns typeof(VipCustomer)
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ard 5

对于第一个,您需要一个实际的实例(即myCustomer),对于第二个,您不需要


Fly*_*wat 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)
Run Code Online (Sandbox Code Playgroud)