無法解釋接下來的程序發生了什麼。 GetType返回我想要返回的類型,而不是原來的類型。這是否意味着我們不能依賴GetType?是運營商是正確的。任何人都可以詳細解釋一下嗎?GetType返回不同於運營商使用的信息
using System;
namespace ConsoleApplication2
{
public class MyClass
{
public Type GetType()
{
return typeof(Program);
}
}
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
if (mc.GetType() == typeof(Program))
{
Console.WriteLine("Confused.");
}
if(mc is Program)
{
Console.WriteLine(mc.GetType()); // Don't get inside the if. Why?
}
}
}
}
更新:我通過C#第三版閱讀的書CLR。在當它解釋了System.Object的不同方法第4章(第2頁),它說
「GetType方法是非虛, ,其防止一個類重寫此 方法和躺在它的類型」
雖然我對第一條語句表示同意,但我對MyClass類型說謊。不是我嗎?
你能否證實,這裏的困惑是,mc.GetType()== typeof運算(計劃)實際評估爲真? – 2010-10-02 05:39:17
是的。實際上它似乎是運算符使用一些不同的機制來檢查類型比GetType()。如果是,機制是什麼?另外上面的程序顯示我們不能相信GetType返回正確的類型。 – Tanmoy 2010-10-02 05:41:43
我認爲你對創建**新**方法(隱藏祖先方法)和**覆蓋**祖先方法之間的區別感到困惑。埃裏克Lippert最近有[博客文章](http://blogs.msdn.com/b/ericlippert/archive/2010/03/29/putting-a-base-in-the-middle.aspx)觸及此(可能還有其他人,但這是我能找到的第一個)。閱讀它可以幫助你瞭解這裏發生了什麼。 – 2010-10-02 08:00:00