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

时间:2008-09-26 13:50:01

标签: c# .net

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

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

7 个答案:

答案 0 :(得分:154)

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

重要区别

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

答案 1 :(得分:27)

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

答案 2 :(得分:20)

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

class VipCustomer : Customer
{
  .....
}

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

答案 3 :(得分: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)

答案 4 :(得分:4)

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

答案 5 :(得分:2)

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

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

答案 6 :(得分: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 
相关问题