我有下一节课:
public class A
{
public int MyProperty { get; set; }
}
Main中的以下代码:
object obj = new A();
Stopwatch sw = Stopwatch.StartNew();
var res = obj as A;
if (res != null)
{
res.MyProperty = 10;
Console.WriteLine("obj is A (as)" + sw.Elapsed);
}
sw.Stop();
Stopwatch sw2 = Stopwatch.StartNew();
if (obj.GetType() == typeof(A))
{
A a = (A)obj;
a.MyProperty = 10;
Console.WriteLine("obj is A (GetType)" + sw2.Elapsed);
}
sw2.Stop();
Stopwatch sw3 = Stopwatch.StartNew();
var isA = obj is A;
if (isA)
{
A a = (A)obj;
a.MyProperty = 19;
Console.WriteLine("obj is A (is)" + sw3.Elapsed);
}
sw3.Stop();
Console.ReadKey();
结果是:
obj is A (as) 00:00:00.0000589
obj is A (GetType) 00:00:00.0000024
obj is A (is) 00:00:00.0000006
关键是运算符“is”的工作速度总是比“as”快。为什么'as'比'is'慢?甚至 GetType() 也比 'as' 快。与 'is' 和 GetType() 相比,什么代表导致此类延迟的 'as' 运算符。