IF语句中的常量值和直接值

时间:2013-03-30 15:37:04

标签: c# const

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

编译时确定ConstantValue + 1吗?

2 个答案:

答案 0 :(得分:4)

是的,它将在编译期间被替换:

C#代码:

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声明如下:

public const int ConstValue = 10;

答案 1 :(得分:1)

是的,ConstantValue + 1在编译时确定。

示例:

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

我们可以用反射器看到这个:

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