2014-10-16 6 views
-2

이 코드 것은암시 적으로 형식 '무효'로 변환 할 수 없습니다 '암시 적으로 형식을 변환 할 수 없습니다 System.Collections.Generic.Dictionary <string,bool>

다음 코드는이 오류가 발생
Dictionary<string, bool> test = new Dictionary<string, bool>(); 
     test.Add("test string", true); 

잘 작동' .Generic.Dictionary

Dictionary<string, bool> test = new Dictionary<string, bool>().Add("test string", true); 

왜? 차이점은 무엇입니까?

답변

4

.Add의 반환 형식이 void

입니다, 마지막 표현은 전체 문장의 반환 값이됩니다.

Dictionary<string, bool> test = new Dictionary<string, bool> 
{ 
    { "test string", true } 
}; 

편집 :

new Dictionary<K, V>()의 반환 값은 당신이 그것을에 .Add.Add 반환 아무것도 당신이 인라인을 수행하는 구문 initialiser 객체를 사용할 수 있습니다 (void)

전화, Dictionary<K, V> 더 정보, 많은 유창한 구문 스타일 프레임 워크는 체인을 허용하기 위해 메서드를 호출 한 객체를 반환합니다.

예 : 자연스럽게

public class SomeFluentThing 
{ 
    public SomeFluentThing DoSomething() 
    { 
     // Do stuff 
     return this; 
    } 

    public SomeFluentThing DoSomethingElse() 
    { 
     // Do stuff 
     return this; 
    } 

} 

그래서 당신이 할 수있는 체인 :

SomeFluentThingVariable.DoSomething().DoSomethingElse(); 
+0

agh .. 반환 유형을 확인하는 것을 잊었습니다. 감사. – PSR

0

Add() 메서드의 반환 값 형식은 Dictionary 클래스의 개체가 아닙니다. 또한 Add() 메서드의 출력을 테스트 객체에 할당 할 수 없습니다.

예를 들어 당신이 이 코드를 사용할 수 없습니다 당신이 전화를 체인하는 경우

Dictionary<string, bool> test = new Dictionary<string, bool>(); 
test = test.Add("test string", true); // Error 
0

Add()에 대한 반환 형식이 너무 void

new Dictionary<string, bool>().Add("test string", true);이다는 오류가 발생하면 Dictionary<string, bool> test에 할당되어 무효이다. 그러므로 새로운 변수가 할 수있는 반면에

Dictionary<string, bool> test = new Dictionary<string, bool>(); 
test.Add("test string", true); 

testDictionary 새로운 할당하고 후자는 Add

0

알리 Sephri.Kh 말했듯이,

new Dictionary<string, bool>(); 

동안 반환에게 사전 인스턴스를 수행 Add 메서드는 새 사전에 새 값을 추가하고 void를 반환하므로 새 변수에 할당 할 수 없습니다.

관련 문제