ProgramingTip

C #에서 줄 계속 문자

bestdevel 2020. 12. 11. 19:14
반응형

C #에서 줄 계속 문자


매우 긴 패키지를 포함하는 변수를 단위 테스트가 있습니다.

질문은 줄 바꿈에 문제가 있고 코드를 읽기 어렵게 코드로 작성하는 방법입니다.

VB에는 줄 계속 문자가 있습니다. C #에 있습니까?


C #을 사용하면 여러 줄로 나눌 수있는 용어는 verbatim literal다음과 같습니다.

string myString = @"this is a
                    test
                   to see how long my string
                   can be



                    and it can be quite long";

& _VB 에서 대안을 찾고 있다면 사용 +하실 수 있습니다.


상수 상수

+연산자를 사용하고 계신가요 사람이 읽을 수있는 줄로 나눕니다. 컴파일러는 모바일이 상수임을 선택하고 타임에 연결합니다. 여기 에서 MSDN C # 프로그래밍 가이드를 참조 하십시오 .

예 :

const string myVeryLongString = 
    "This is the opening paragraph of my long string. " +
    "Which is split over multiple lines to improve code readability, " +
    "but is in fact, just one long string.";

IL_0003: ldstr "This is the opening paragraph of my long string. Which is split over multiple lines to improve code readability, but is in fact, just one long string."

모바일 변수

보간을 사용 문자열하여 값을 문자열로 대체 할 때 $문자 는 대체가 필요한 앞에 와야합니다 .

var interpolatedString = 
    "This line has no substitutions. " +
    $" This line uses {count} widgets, and " +
    $" {CountFoos()} foos were found.";

이것은 그러나 문자열 을 여러 번 호출 하고 결과적으로 문자열을 연결함으로써 성능이 저하string.Format됩니다 (으로 표시됨 ***).

IL_002E:  ldstr       "This line has no substitutions. "
IL_0033:  ldstr       " This line uses {0} widgets, and "
IL_0038:  ldloc.0     // count
IL_0039:  box         System.Int32
IL_003E:  call        System.String.Format ***
IL_0043:  ldstr       " {0} foos were found."
IL_0048:  ldloc.1     // CountFoos
IL_0049:  callvirt    System.Func<System.Int32>.Invoke
IL_004E:  box         System.Int32
IL_0053:  call        System.String.Format ***
IL_0058:  call        System.String.Concat ***

$@단일 어디에도 제공되지 않는{} 성능 문제를 피하는 데 사용할 수 없습니다 공백이 내부에 배치되지 않는 한 (이상하게 보임 IMO) Neil Knight의 답변과 동일한 문제가 있습니다. 이것은 줄 구분에 공백을 포함하기 때문입니다. :

var interpolatedString = $@"When breaking up strings with `@` it introduces
    <- [newLine and whitespace here!] each time I break the string.
    <- [More whitespace] {CountFoos()} foos were found.";

삽입 된 공백은 쉽게 사용할 수 있습니다.

IL_002E:  ldstr       "When breaking up strings with `@` it introduces
    <- [newLine and whitespace here!] each time I break the string.
    <- [More whitespace] {0} foos were found."

대안은로 되 돌리는 것 string.Format입니다. 여기에서 형식 지정 절차는 내 초기 답변에 따라 단일 상수입니다.

const string longFormatString = 
    "This is the opening paragraph of my long string with {0} chars. " +
    "Which is split over multiple lines to improve code readability, " +
    "but is in fact, just one long string with {1} widgets.";

그리고 다음과 같이 평가됩니다.

string.Format(longFormatString, longFormatString.Length, CountWidgets());

그러나 유지하기가 여전히 까다로울 수 있습니다.


@"string here
that is long you mean"

하지만 조심하세요.

@"string here
           and space before this text
     means the space is also a part of the string"

또한 이동의 항목을 이스케이프합니다.

@"c:\\folder" // c:\\folder
@"c:\folder" // c:\folder
"c:\\folder" // c:\folder

관련


축어 리터럴을 사용할 수 있습니다.

const string test = @"Test
123
456
";

그러나 첫 번째 줄의 들여 쓰기는 까다 롭고 /보기 흉합니다.


다음 방법 중 하나를 사용합니다.

    string s = @"loooooooooooooooooooooooong loooooong
                  long long long";

string s = "loooooooooong loooong" +
           " long long" ;

그의 훌륭한 답변에서 StuartLC는 관련 질문에 대한 답변인용 {expression}하고 보간 된 내부에 줄 바꿈을 배치하면 "이상하게 투표"라고 언급합니다 . 대부분 동의하지만, 불쾌한 소스 코드의 효과는 다소 유효 할 수 있습니다-어떤 실행 결과없이-전용하여 {expression}어떤 해결 블록 default(String), 즉, null( 즉, 하지 String.Empty ).

(사소하지만) 요점은 대신 전용 토큰을 사용하여 실제 표현 내용을 엉망으로 만들거나 오염되지 않는 것입니다. 따라서 예를 들어 상수를 선언하는 경우 :

const String more = null;

... 다음과 같이 소스 코드에서보기에는 너무 긴 줄이 있습니다.

var s1 = $"one: {99 + 1} two: {99 + 2} three: {99 + 3} four: {99 + 4} five: {99 + 5} six: {99 + 6}";

... 대신 이렇게 쓸 수 있습니다.

var s2 = $@"{more
    }one: {99 + 1} {more
    }two: {99 + 2} {more
    }three: {99 + 3} {more
    }four: {99 + 4} {more
    }five: {99 + 5} {more
    }six: {99 + 6}";

다른 "이상한"방식을 선호 할 수도 있습니다.

// elsewhere:
public const String Ξ = null;  // Unicode '\u039E', Greek 'Capital Letter Xi'

// anywhere:
var s3 = $@"{
           Ξ}one: {99 + 1} {
           Ξ}two: {99 + 2} {
           Ξ}three: {99 + 3} {
           Ξ}four: {99 + 4} {
           Ξ}five: {99 + 5} {
           Ξ}six: {99 + 6}";

세 가지 예제 모두 string실행에 동일한 결과 생성합니다 .

one: 100 two: 101 three: 102 four: 103 five: 104 six: 105

스튜어트가 제안했듯이 IL은 성능 +문자열을 연결 하는 사용하지 않음 으로써이 두 예에서 모두 유지 됩니다. 새 예제에서 더 형식이있는 파일에 저장 참조되는 null 자리 표시 초기화되지 않습니다. 비교를 위해 위의 두 예에 대한 IL이 있습니다.

첫 번째 예는 IL

ldstr "one: {0} two: {1} three: {2} four: {3} five: {4} six: {5}"
ldc.i4.6
newarr object
dup
ldc.i4.0
ldc.i4.s 100
box int32
stelem.ref
dup
ldc.i4.1
ldc.i4.s 101
box int32
stelem.ref
dup
ldc.i4.2
ldc.i4.s 102
box int32
stelem.ref
dup
ldc.i4.3
ldc.i4.s 103
box int32
stelem.ref
dup
ldc.i4.4
ldc.i4.s 104
box int32
stelem.ref
dup
ldc.i4.5
ldc.i4.s 105
box int32
stelem.ref
call string string::Format(string, object[])

두 번째 예의 경우 IL

ldstr "{0}one: {1} {2}two: {3} {4}three: {5} {6}four: {7} {8}five: {9} {10}six: {11}"
ldc.i4.s 12
newarr object
dup
ldc.i4.1
ldc.i4.s 100
box int32
stelem.ref
dup
ldc.i4.3
ldc.i4.s 101
box int32
stelem.ref
dup
ldc.i4.5
ldc.i4.s 102
box int32
stelem.ref
dup
ldc.i4.7
ldc.i4.s 103
box int32
stelem.ref
dup
ldc.i4.s 9
ldc.i4.s 104
box int32
stelem.ref
dup
ldc.i4.s 11
ldc.i4.s 105
box int32
stelem.ref
call string string::Format(string, object[])

다른 변수를 선언 한 경우 다음과 같은 간단한 방법을 사용하십시오.

Int salary=2000;

String abc="I Love Pakistan";

Double pi=3.14;

Console.Writeline=salary+"/n"+abc+"/n"+pi;
Console.readkey();

참고 URL : https://stackoverflow.com/questions/4086138/line-continue-character-in-c-sharp

반응형