2013-04-12 2 views
1

는이 주어동일한 val을 사용하여 두 개의 별도 string.Format 자리 표시자를 대체하는 경우 두 번 제공해야합니까?</p> <pre><code>string msg = string.Format("Duckbill {0} Platypus has not been loaded. Fetch Duckbill {1}'s Platypus then continue.", userDuckbill, userDuckbill); </code></pre> <p>... 대신이 일을 충분 :

string msg = string.Format("Duckbill {0} Platypus has not been loaded. Fetch Duckbill {1}'s Platypus then continue.", userDuckbill); 

?

+0

테스트 순간에 stackoverflow에서 몇 순간을 절약 할 수있었습니다. 이 경우에 물어 보는 것보다 테스트하는 것이 더 쉬울 것입니다. – spender

+0

제 경우는 아닙니다; 가장 단순한 것을 테스트하는 데 몇 분이 걸립니다. –

+0

나는 http://www.linqpad.net을 추천한다 – spender

답변

11

매개 변수를 여러 번 지정할 수 있습니다. 대신 다음을 사용하십시오 :

official documentation에는 이와 같은 몇 가지 예가 있습니다. 여기에 하나를 그냥 :

string formatString = " {0,10} ({0,8:X8})\n" + 
         "And {1,10} ({1,8:X8})\n" + 
         " = {2,10} ({2,8:X8})"; 
    int value1 = 16932; 
    int value2 = 15421; 
    string result = String.Format(formatString, value1, value2, value1 & value2); 
2

사용 {0} 두 번 :

string msg = string.Format(
    "Duckbill {0} Platypus has not been loaded. Fetch Duckbill {0}'s Platypus then continue.", 
    userDuckbill); 

두 번째 코드 샘플은 다음과 같은 메시지와 함께 FormatException 초래 :

인덱스 (제로 기준) 이상이어야합니다 0보다 크거나 같고 인수 목록의 크기는 보다 작습니다.

따라서 {n}을 사용할 때마다 형식 문자열 뒤에 적어도 n 개의 매개 변수가 있어야합니다. n 이상을 갖는 것은 쓸모가 없습니다.