2011-07-17 4 views
1

지난 번 비슷한 질문을했지만, 로직 문 앞에 변수 값을 초기화하고 설정하면 로직 문에서 생성 된 값을 사용할 수 있습니다.if 문에서 선언 된 변수를 사용하는 방법은 무엇입니까?

이번에는 연결 문자열이 비어 있는지 여부에 따라 두 가지 메서드 오버로드 중 하나를 호출하고 싶습니다. 그렇게.

if (ConnectionString != "") // if there is something in the config file work with it 
{ 
    SqlConnection dataConnection = new SqlConnection(ConnectionString); 
} 
else 
{ 
    SqlConnection dataConnection = new SqlConnection(); 
} 

try { 
    // ... 

문제는 try 블록의 모든 것이 dataConnection에 대해 알지 못하기 때문에 실패한다는 것입니다.

어떻게 작동 시키려면 어떻게해야합니까?

SqlConnection dataConnection = !string.IsNullOrEmpty(ConnectionString) 
    ? new SqlConnection(ConnectionString) : new SqlConnection(); 

을 또는 :

+3

연결 문자열이없는 경우 어디서 오는 것으로 예상합니까? SqlConnection이 그것을 만들거나 하늘에서 떨어질 것이라고 생각하지 마십시오. 'else' 조건에서 당신은 무엇을합니까? 추락? –

+0

예 연결 문자열 작성기가 try 블록에 있습니다. – Rob

+0

멋진 답변을 보내 주신 모든 분들께 감사드립니다! 지금은 훨씬 더 명확 해. – Rob

답변

3

이 (초기화)를 선언 외부 :

SqlConnection conn; 
if(string.IsNullOrEmpty(connectionString)) { 
    conn = new SqlConnection(); 
} else { 
    conn = new SqlConnection(connectionString); 
} 

을 논리는 간단 경우 조건을도 가능합니다.

SqlConnection conn = string.IsNullOrEmpty(connectionString) 
    ? new SqlConnection() : new SqlConnection(connectionString); 

후자는 using 블록으로 훨씬 쉽게 사용할 수 있습니다. 인라인으로 처리 할 수 ​​있기 때문입니다.

SqlConnection dataConnection; 
if (ConnectionString != "") // if there is something in the config file work with it 
{ 
    dataConnection = new SqlConnection(ConnectionString); 
} 
else 
{ 
    dataConnection = new SqlConnection(); 
} 
6

이 같은 그것을 할 수

SqlConnection dataConnection; 
if (string.IsNullOrEmpty(ConnectionString)) 
{ 
    dataConnection = new SqlConnection(ConnectionString); 
} 
else 
{ 
    dataConnection = new SqlConnection(); 
} 
1

당신이 경우 블록 외부 변수를 가지고 있어야 statement 그리고 나서 if 문 안에 사용하고 사용해야 할 때 null이 아닌지 확인하십시오.

SqlConnection dataConnection = null; 
if (ConnectionString != "") // if there is something in the config file work with it 
{ 
    dataConnection = new SqlConnection(ConnectionString); 
} 
else 
{ 
    dataConnection = new SqlConnection(); 
} 
try 
{ 
    if(dataConnection != null) 
     DoWhatYouWant(); 
} 
1

내가 문

SqlConnection dataConnection = null; 
    if (ConnectionString != "") // if there is something in the config file work with it 
     { 
      dataConnection = new SqlConnection(ConnectionString); 
     } 
     else 
     { 
      dataConnection = new SqlConnection(); 
     } 
     try 
     { 
1

당신은 null 값 밖으로 측면의 경우와 변수를 선언 할 경우 이전에 연결을 정의해야한다고 생각 :

관련 문제