Он не оптимизирован под IL в сборках отладки или выпуска.
простой тест на C #:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RedundantCastTest
{
class Program
{
static object get()
{ return "asdf"; }
static void Main(string[] args)
{
object obj = get();
if ((string)obj == "asdf")
Console.WriteLine("Equal: {0}, len: {1}", obj, ((string)obj).Length);
}
}
}
Соответствующий IL (обратите внимание на несколько castclass
инструкций):
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 3
.locals init (
[0] object obj,
[1] bool CS$4$0000)
L_0000: nop
L_0001: call object RedundantCastTest.Program::get()
L_0006: stloc.0
L_0007: ldloc.0
L_0008: castclass string
L_000d: ldstr "asdf"
L_0012: call bool [mscorlib]System.String::op_Equality(string, string)
L_0017: ldc.i4.0
L_0018: ceq
L_001a: stloc.1
L_001b: ldloc.1
L_001c: brtrue.s L_003a
L_001e: ldstr "Equal: {0}, len: {1}"
L_0023: ldloc.0
L_0024: ldloc.0
L_0025: castclass string
L_002a: callvirt instance int32 [mscorlib]System.String::get_Length()
L_002f: box int32
L_0034: call void [mscorlib]System.Console::WriteLine(string, object, object)
L_0039: nop
L_003a: ret
}
Он также не оптимизирован из IL в сборке выпуска:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 3
.locals init (
[0] object obj)
L_0000: call object RedundantCastTest.Program::get()
L_0005: stloc.0
L_0006: ldloc.0
L_0007: castclass string
L_000c: ldstr "asdf"
L_0011: call bool [mscorlib]System.String::op_Equality(string, string)
L_0016: brfalse.s L_0033
L_0018: ldstr "Equal: {0}, len: {1}"
L_001d: ldloc.0
L_001e: ldloc.0
L_001f: castclass string
L_0024: callvirt instance int32 [mscorlib]System.String::get_Length()
L_0029: box int32
L_002e: call void [mscorlib]System.Console::WriteLine(string, object, object)
L_0033: ret
}
Ни один из этих случаев не означает, что приведение не оптимизируется при создании собственного кода - вам нужно посмотреть на фактическую сборку машины. то есть, запустив ngen и разобрав его. Я был бы очень удивлен, если бы он не был оптимизирован.
Несмотря ни на что, я приведу Прагматичный программист и теорему о разбитом окне: когда вы видите разбитое окно, исправьте его.