if(obj is T) { T value = (T) obj; }
T value = obj as T; if(value !=null) { }
测试例子:
class TestClass { } class Program { static Stopwatch sw_Timer = new Stopwatch(); const int NUM = 100000; static int? TestIntType; static TestClass testClass = new TestClass(); static void Main() { Console.WriteLine("值类型测试."); sw_Timer.Restart(); for (int i = 0; i < NUM; i++) { object obj = i + 1; if (obj is int) { TestIntType = (int?)obj1; } } sw_Timer.Stop(); Console.WriteLine("Is运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks); sw_Timer.Restart(); for (int i = 0; i < NUM; i++) { object obj = i + 1; TestIntType = obj as int?; if (TestIntType != null) { } } sw_Timer.Stop(); Console.WriteLine("As运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks); Console.WriteLine("引用类型测试."); sw_Timer.Restart(); for (int i = 0; i < NUM; i++) { object obj = testClass; if (obj is TestClass) { TestClass objTest = (TestClass)obj; } } sw_Timer.Stop(); Console.WriteLine("Is运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks); sw_Timer.Restart(); for (int i = 0; i < NUM; i++) { object obj = testClass; TestClass objTest = obj as TestClass; if (objTest != null) { } } sw_Timer.Stop(); Console.WriteLine("As运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks); Console.ReadKey(); } }
测试结果
来源:博客园
作者:njit_77
链接:https://www.cnblogs.com/njit-77/archive/2019/09/05/11469054.html