C#中的TryGetValue对字符串不起作用,是吗?

Bla*_*man 1 c# casting

该对象Row是一个类,它具有Values一个Dictionary 属性.

以下是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;
}
Run Code Online (Sandbox Code Playgroud)

如果我做:

user.Username = user.Values.TryGetValue<string>("Username");
Run Code Online (Sandbox Code Playgroud)

如果键"username"不在Dictionary中,则会发生这种情况.

我得到一个例外,无效的演员:

出现以下错误:

System.InvalidCastException:指定的强制转换无效.

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

TryGetValue[T](Row row, String key) 
Run Code Online (Sandbox Code Playgroud)

所以我猜TryGetValue对字符串不起作用?

Dan*_*Tao 5

您是否有可能在词典中输入一个"Username"键,其值不是字符串

我已经为您的方法添加了评论,说明了这可能会导致您的问题.

// 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;
}
Run Code Online (Sandbox Code Playgroud)