它们都是一样的,没有区别 (我希望它是一个类而不是结构,在你的问题中,否则它不会编译)
假设你有:
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");
}
}
这是来自 ildasm 的 IL
.method private hidebysig static void Main(string[] 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