[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()。因为接口本身是无法实例化的,其实例的值实际上为继承了接口类型的实例。

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