programing tip

C #에서 선행 문없이 {} 코드 블록을 허용하는 이유는 무엇입니까?

itbloger 2020. 9. 20. 09:07
반응형

C #에서 선행 문없이 {} 코드 블록을 허용하는 이유는 무엇입니까?


왜 C #을 허용 않는 앞의 문이없는 코드 블록 (예를 들어 if, else, for, while)?

void Main()
{
    {   // any sense in this?
        Console.Write("foo");
    }
}

당신이주는 맥락에서는 의미가 없습니다. 콘솔에 상수 문자열을 쓰는 것은 프로그램 흐름의 어느 곳에서나 동일한 방식으로 작동합니다. 1

대신, 일반적으로 일부 지역 변수의 범위를 제한하는 데 사용합니다. 이것은 여기여기에서 더 자세히 설명 됩니다 . 간단한 예 João Angelo의 답변Chris Wallis의 답변 을 참조하십시오. C 스타일 구문을 사용하는 다른 언어에도 똑같이 적용되지만이 질문과 관련이 있다는 것은 아닙니다.


1 물론, 전혀 예상치 못한 Console일을하는 Write()방법 으로 재미 있고 자신 만의 수업을 만들기로 결정하지 않는 한 .


{ ... }로컬 변수에 대한 새로운 범위의 도입 적어도 부작용을 갖는다.

나는 switch각 케이스에 대해 다른 범위를 제공하기 위해 문 에서 사용하는 경향이 있으며, 이런 식으로 사용의 가능한 가장 가까운 위치에서 동일한 이름으로 지역 변수를 정의하고 케이스 수준에서만 유효 함을 나타낼 수 있습니다.


범위정의 하기 위해 중괄호를 사용하는 많은 C 구문 언어의 논리적 부작용 이라기보다는 C # 기능 이 아닙니다 .

귀하의 예에서 중괄호는 전혀 효과가 없지만 다음 코드에서는 변수의 범위 및 가시성을 정의합니다.

이것은 i가 첫 번째 블록에서 범위를 벗어나고 다음 블록에서 다시 정의되기 때문에 허용 됩니다.

{
    {
        int i = 0;
    }

    {
        int i = 0;
    }
}

이 작업은 허용되지 않습니다 내가 범위 밖으로 떨어 더 이상 외부 범위에서 볼 수없는 것처럼 :

{
    {
        int i = 0;
    }

    i = 1;
}

기타 등등.


{}여러 문장을 포함 할 수있는 문장으로 생각 합니다.

하나의 문이 뒤에 오는 부울 식으로 존재하는 if 문을 고려하십시오 . 이것은 작동합니다.

if (true) Console.Write("FooBar");

이것은 잘 작동합니다.

if (true)
{
  Console.Write("Foo");
  Console.Write("Bar");
}

내가 착각하지 않았다면 이것을 블록 문이라고합니다.

Since {} can contain other statements it can also contain other {}. The scope of a variable is defined by it's parent {} (block statement).

The point that I'm trying to make is that {} is just a statement, so it doesn't require an if or whatever...


The general rule in C-syntax languages is "anything between { } should be treated as a single statement, and it can go wherever a single statement could":

  • After an if.
  • After a for, while or do.
  • Anywhere in code.

For all intents and purposes, it's as the language grammar included this:

     <statement> :== <definition of valid statement> | "{" <statement-list> "}"
<statement-list> :== <statement> | <statement-list> <statement>

That is, "a statement can be composed of (various things) or of an opening brace, followed by a statement list (which may include one or more statements), followed by a closed brace". I.E. "a { } block can replace any statement, anywhere". Including in the middle of code.

Not allowing a { } block anywhere a single statement can go would actually have made the language definition more complex.


Because C++ (and java) allowed code blocks without a preceding statement.

C++ allowed them because C did.

You could say it all comes down to the fact that USA programme language (C based) design won rather than European programme language (Modula-2 based) design.

(Control statements act on a single statement, statements can be groups to create new statements)


// if (a == b)
// if (a != b)
{
    // do something
}

1Because...Its Maintain the Scope Area of the statement.. or Function, This is really useful for mane the large code..

{
    {
        // Here this 'i' is we can use for this scope only and out side of this scope we can't get this 'i' variable.

        int i = 0;
    }

    {
        int i = 0;
    }
}

enter image description here


You asked "why" C# allows code blocks without preceeding statements. The question "why" could also be interpreted as "what would be possible benefits of this construct?"

Personally, I use statement-less code blocks in C# where readability is greatly improved for other developers, while keeping in mind that the code block limits the scope of local variables. For example, consider the following code snippet, which is a lot easier to read thanks to the additional code blocks:

OrgUnit world = new OrgUnit() { Name = "World" };
{
    OrgUnit europe = new OrgUnit() { Name = "Europe" };
    world.SubUnits.Add(europe);
    {
        OrgUnit germany = new OrgUnit() { Name = "Germany" };
        europe.SubUnits.Add(germany);

        //...etc.
    }
}
//...commit structure to DB here

I'm aware that this could be solved more elegantly by using methods for each structure level. But then again, keep in mind that things like sample data seeders usually need to be quick.

So even though the code above is executed linearly, the code structure represents the "real-world" structure of the objects, thus making it easier for other developers to understand, maintain and extend.

참고URL : https://stackoverflow.com/questions/6136853/why-does-c-sharp-allow-code-blocks-without-a-preceding-statement

반응형