2
if (myValue > ConstantValue + 1)
{
    // do some stuff
}

Is ConstantValue + 1 determined at compile time?

4

2 回答 2

4

Yes, it will be replaced during compilation:

C# Code:

if (value <= ConstValue)
    Console.WriteLine("Test1");

if (value <= ConstValue + 1)
    Console.WriteLine("Test2");

IL:

IL_000c: ldloc.0
IL_000d: ldc.i4.s 10
IL_000f: cgt
IL_0011: stloc.1
IL_0012: ldloc.1
IL_0013: brtrue.s IL_0020

IL_0015: ldstr "Test1"
IL_001a: call void [mscorlib]System.Console::WriteLine(string)
IL_001f: nop

IL_0020: ldloc.0
IL_0021: ldc.i4.s 11
IL_0023: cgt
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: brtrue.s IL_0034

IL_0029: ldstr "Test2"
IL_002e: call void [mscorlib]System.Console::WriteLine(string)
IL_0033: nop

ConstValue is declared as following:

public const int ConstValue = 10;
于 2013-03-30T15:45:34.690 回答
1

Yes, ConstantValue + 1 determined at compile time.

Example:

 static void Main(string[] args)
        {
            const int count = 1;
            int myValue = 3;
            if (myValue > count + 1)
            {
                Console.WriteLine(count);
            }
        }

we can see this with reflector:

private static void Main(string[] args)
{
    int myValue = 3;
    if (myValue > 2)
    {
        Console.WriteLine(1);
    }
}
于 2013-03-30T16:06:20.743 回答