相同点
两者的返回值都是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()
。因为接口本身是无法实例化的,其实例的值实际上为继承了接口类型的实例。