[英]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.