[英]What is the difference between myCustomer.GetType() and typeof(Customer) in C#?
我已经看到我在维护的一些代码中完成了两个,但不知道区别。 有吗?
让我补充一点,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方法,并在运行时解析。 第一个是在需要使用已知类型时使用,第二个是在不知道它是什么时获取对象的类型。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.