兩者的他們都一樣,沒有什麼區別(我希望它的一類不是一個結構,在你的問題,否則將無法編譯)
假設您有:
class Test
{
public int MyProperty { get; set; }
public int SomeOther { get; set; }
}
class Program
{
static void Main(string[] args)
{
object obj = new Test();
if (obj as Test != null)
{
Console.WriteLine("test1");
}
if (obj is Test)
{
Console.WriteLine("test2");
}
}
如果您在ILSpy查看代碼。
private static void Main(string[] args)
{
object obj = new Test();
if (obj is Test)
{
Console.WriteLine("test1");
}
if (obj is Test)
{
Console.WriteLine("test2");
}
}
這裏是IL從ILDASM
。方法私人hidebysig靜態無效的主要(字串[] args)CIL管理
{
.entrypoint
// Code size 43 (0x2b)
.maxstack 1
.locals init ([0] object obj)
IL_0000: newobj instance void ILTest.Test::.ctor()
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: isinst ILTest.Test
IL_000c: brfalse.s IL_0018
IL_000e: ldstr "test1"
IL_0013: call void [mscorlib]System.Console::WriteLine(string)
IL_0018: ldloc.0
IL_0019: isinst ILTest.Test
IL_001e: brfalse.s IL_002a
IL_0020: ldstr "test2"
IL_0025: call void [mscorlib]System.Console::WriteLine(string)
IL_002a: ret
} // end of method Program::Main
有非常有用的類('System.Diagnostics.Stopwatch')來分析這樣的事情。 – Leri
如果這確實是應用程序性能的瓶頸,那麼問題就更加深入了。 –
您應該閱讀以下內容:http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html –