相同點
兩者的返回值都是Type
類型。
https://docs.microsoft.com/zh-cn/dotnet/api/system.type?view=netcore-3.1
區別
typeof
是關鍵字,GetType
是方法。typeof
用於類型,即class
。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()
。因爲接口本身是無法實例化的,其實例的值實際上爲繼承了接口類型的實例。