2012-06-24 3 views
2

InvalidCastException이 표시되며 이유를 모르겠습니다.InvalidCastException이 발생하는 이유가 확실하지 않습니다.

public static void AddToTriedList(string recipeID) 
{ 
    IList<string> triedIDList = new ObservableCollection<string>(); 
    try 
    { 
     IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings; 
     if (!settings.Contains("TriedIDList")) 
     { 
      settings.Add("TriedIDList", new ObservableCollection<Recipe>()); 
      settings.Save(); 
     } 
     else 
     { 
      settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList); 
     } 
     triedIDList.Add(recipeID); 
     settings["TriedIDList"] = triedIDList; 
     settings.Save(); 
    } 
    catch (Exception e) 
    { 
     Debug.WriteLine("Exception while using IsolatedStorageSettings in AddToTriedList:"); 
     Debug.WriteLine(e.ToString()); 
    } 
} 

AppSettings.cs : 여기

예외 제기 코드입니다 (추출물)

// The isolated storage key names of our settings 
const string TriedIDList_KeyName = "TriedIDList"; 

// The default value of our settings 
IList<string> TriedIDList_Default = new ObservableCollection<string>(); 

... 

/// <summary> 
/// Property to get and set the TriedList Key. 
/// </summary> 
public IList<string> TriedIDList 
{ 
    get 
    { 
     return GetValueOrDefault<IList<string>>(TriedIDList_KeyName, TriedIDList_Default); 
    } 
    set 
    { 
     if (AddOrUpdateValue(TriedIDList_KeyName, value)) 
     { 
      Save(); 
     } 
    } 
} 

GetValueOrDefault<IList<string>>(TriedIDList_KeyName, TriedIDList_Default)AddOrUpdateValue(TriedIDList_KeyName, value)는 Microsoft에서 권장하는 일반적인 방법이 있습니다를, 전체 코드 here을 찾을 수 있습니다.

편집 : 나는이 라인에서 예외를 가지고 :

settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList); 
+0

* * 예외는 무엇입니까? 어느 선 이요? – Will

+0

오류를 생성하는 특정 행을 식별하기 위해 디버거를 밟으면 매우 유용합니다. – paulsm4

+0

죄송합니다. 작성하는 것을 잊어 버립니다. 예외는 여기에서 발생합니다 : settings.TryGetValue > ("TriedIDList", out triedIDList); –

답변

3

당신은 추가 할을 ObservableCollection<Recipe>settings 당신에게 : 다음

settings.Add("TriedIDList", new ObservableCollection<Recipe>()); 
          // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

하지만 당신은 아주이다, 다시 IList<string> 읽고 분명히 다른 유형 :

settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList); 
        // ^^^^^^^^^^^^^ 

당신의 d triedIDList의 eclaration은 다음과 같습니다

IList<string> triedIDList = new ObservableCollection<string>(); 
// ^^^^^^^^^^^^^    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

시작으로, 하나 개의 유형을 결정하고 다음 (당신이 꼭 필요한 것은 생각하더라도) 모든 장소에서 동일한 유형을 사용하는 InvalidCastException 간다 있는지 떨어져.

+0

오 하나님, ObservableCollection 이어야합니다! 내가 편집 할거야 ... –

+0

그것은 작동합니다! 정말 고마워! : D –

+1

또한 작은 샌드 박스 프로젝트를 설정하고 몇 가지 실험을 실행하여 제네릭 형식 (및 배열도 가능)에서 허용되는 변환 유형을 확인하고 그렇지 않은 형식을 확인하는 것이 좋습니다. 그것은 항상 유용한 지식입니다! ;) – stakx

관련 문제