[C#學習筆記] - typeof與GetType()的區別

相同點

兩者的返回值都是Type類型。

https://docs.microsoft.com/zh-cn/dotnet/api/system.type?view=netcore-3.1

區別

  1. typeof是關鍵字,GetType是方法。
  2. typeof用於類型,即class
  3. GetType用於實例,即class instace
public interface Animal{}

public class Dog : Animal{}

public class Cat : Animal{}

int a = 1;
Console.WriteLine($"a vs int {a.GetType() == typeof(int)}");

Animal a1 = new Dog();
Animal a2 = new Cat();

Console.WriteLine($"a1 vs Animal {a1.GetType() == typeof(Animal)}");
Console.WriteLine($"a2 vs Animal {a2.GetType() == typeof(Animal)}");
Console.WriteLine($"a1 vs Dog {a1.GetType() == typeof(Dog)}");
Console.WriteLine($"a2 vs Dog {a2.GetType() == typeof(Dog)}");
Console.WriteLine($"a1 vs Cat {a1.GetType() == typeof(Cat)}");
Console.WriteLine($"a2 vs Cat {a2.GetType() == typeof(Cat)}");
Console.WriteLine($"a1 vs a2 {a1.GetType() == a2.GetType()}");

在這裏插入圖片描述
由上訴例子可知,在使用接口的場景下,需要注意,typeof(接口)不同於接口實例.GetType()。因爲接口本身是無法實例化的,其實例的值實際上爲繼承了接口類型的實例。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章