1

文字列の割り当てに興味があります。という定数がある場合mystring = "test"、新しいデータを割り当てずに、アプリケーションのどこでも「test」を使用できますか? 以下を参照してください。このメソッドは新しいデータを割り当てますか?

const string mystring = "test"
void test()
{
    for(int i = 0; i < 100000;i++)
    {
        allocationTest();
    }        
}

void allocationTest()
{
    Console.Write("test");
}
4

2 に答える 2

4

No, the method will not allocate any data.

The compiler will consolidate any duplicate string literals, so the two tring literals "test" will actually be one string that is created when the application starts.

Also, even if the string wouldn't exist in two places, a string literal is never allocated when you use it, it's allocated when the application starts. Having the constant that references the string makes no difference for the string literal used in the method.

于 2013-04-21T21:49:03.043 に答える