2010-05-28 36 views
1

對象是一個類,它有一個屬性Values這是一個字典。C#中的TryGetValue不適用於字符串,是嗎?

以下是Values屬性的擴展方法。

public static T TryGetValue<T>(this Row row, string key) 
{ 
return TryGetValue(row, key, default(T)); 
} 

public static T TryGetValue<T>(this Row row, string key, T defaultValue) 
{ 
    object objValue; 

    if (row.Values.TryGetValue(key, out objValue)) 
    { 
     return (T)objValue; 
    } 

    return defaultValue; 
} 

如果我做的:

user.Username = user.Values.TryGetValue<string>("Username"); 

這happends如果密鑰 「用戶名」 是不是在字典。

我得到一個異常,無效的轉換:

以下錯誤內容時發生:

System.InvalidCastException:指定的轉換無效。

TryGetValue[T](Row row, String key, T defaultValue) 

TryGetValue[T](Row row, String key) 

所以我想TryGetValue不處理字符串?

+0

你可能使用T objValue = default(T);因爲你使用的是通用簽名。 – Pat 2010-05-28 15:23:53

回答

3

如果關鍵字「用戶名」在字典中有相應的字符串值,或者根本不在字典中,它應該可以正常工作。

您收到InvalidCastException的事實表明"Username"密鑰的值不是字符串。

+0

還有另一個超載我沒有抱歉。 – Blankman 2010-05-28 15:08:46

+0

Josh的答案中的鏈接是否指向某個東西? – Blankman 2010-05-28 15:11:05

+1

@Blankman:我建議你編輯你的帖子來澄清:1)超負荷; 2)Row是什麼 - 你說它是一個* Dictionary *類型的對象*,但它顯然是* type *而不是對象; 3)你得到的例外。 – 2010-05-28 15:12:20

5

是否有可能您的字典中有關鍵字「用戶名」,其值爲而非字符串

我已經向您的方法添加了註釋,說明這可能導致您的問題。

// I'm going to go ahead and assume your Values property 
// is a Dictionary<string, object> 
public static T TryGetValue<T>(this Row row, string key, T defaultValue) 
{ 
    // objValue is declared as object, which is fine 
    object objValue; 

    // this is legal, since Values is a Dictionary<string, object>; 
    // however, if TryGetValue returns true, it does not follow 
    // that the value retrieved is necessarily of type T (string) -- 
    // it could be any object, including null 
    if (row.Values.TryGetValue(key, out objValue)) 
    { 
     // e.g., suppose row.Values contains the following key/value pair: 
     // "Username", 10 
     // 
     // then what you are attempting here is (string)int, 
     // which throws an InvalidCastException 
     return (T)objValue; 
    } 

    return defaultValue; 
} 
相關問題