我见过很多人使用以下代码:
Type t = obj1.GetType();
if (t == typeof(int))
// Some code here
但我知道你也可以这样做:
if (obj1.GetType() == typeof(int))
// Some code here
或者这个:
if (obj1 is int)
// Some code here
就我个人而言,我觉得最后一个是最干净的,但我有什么遗漏吗?哪一个最好用,还是个人喜好?
我有一个要比较的Type属性,无法使用它(例如my_Type是_BaseTypetoLookFor),但我可以使用这些属性:
base_type.IsInstanceOfType(derived_object);
base_type.IsAssignableFrom(derived_type);
derived_type.IsSubClassOf(base_type);
请注意,在比较相同类型时,IsInstanceOfType和IsAssignableFrom返回true,其中IsSubClassOf将返回false。IsSubclassOf不适用于接口,而其他两个则适用
public class Animal {}
public interface ITrainable {}
public class Dog : Animal, ITrainable{}
Animal dog = new Dog();
typeof(Animal).IsInstanceOfType(dog); // true
typeof(Dog).IsInstanceOfType(dog); // true
typeof(ITrainable).IsInstanceOfType(dog); // true
typeof(Animal).IsAssignableFrom(dog.GetType()); // true
typeof(Dog).IsAssignableFrom(dog.GetType()); // true
typeof(ITrainable).IsAssignableFrom(dog.GetType()); // true
dog.GetType().IsSubclassOf(typeof(Animal)); // true
dog.GetType().IsSubclassOf(typeof(Dog)); // false
dog.GetType().IsSubclassOf(typeof(ITrainable)); // false
性能测试类型of()与GetType():
using System;
namespace ConsoleApplication1
{
class Program
{
enum TestEnum { E1, E2, E3 }
static void Main(string[] args)
{
{
var start = DateTime.UtcNow;
for (var i = 0; i < 1000000000; i++)
Test1(TestEnum.E2);
Console.WriteLine(DateTime.UtcNow - start);
}
{
var start = DateTime.UtcNow;
for (var i = 0; i < 1000000000; i++)
Test2(TestEnum.E2);
Console.WriteLine(DateTime.UtcNow - start);
}
Console.ReadLine();
}
static Type Test1<T>(T value) => typeof(T);
static Type Test2(object value) => value.GetType();
}
}
调试模式下的结果:
00:00:08.4096636
00:00:10.8570657
释放模式下的结果:
00:00:02.3799048
00:00:07.1797128
当您想在编译时获取类型时,请使用typeof。如果要在执行时获取类型,请使用GetType。很少有任何情况可以使用,因为它进行了强制转换,而且在大多数情况下,最终还是会强制转换变量。
还有第四个选项你还没有考虑(特别是如果你要将一个对象转换为你找到的类型);即用作。
Foo foo = obj as Foo;
if (foo != null)
// your code here
这只使用一个强制转换,而此方法:
if (obj is Foo)
Foo foo = (Foo)obj;
需要两个。
更新(2020年1月):
从C#7+开始,您现在可以内联转换,因此“is”方法现在也可以在一次转换中完成。
例子:
if(obj is Foo newLocalFoo)
{
// For example, you can now reference 'newLocalFoo' in this local scope
Console.WriteLine(newLocalFoo);
}