c# - C# 中的 TryGetValue 不适用于字符串,是吗?

标签 c# casting

对象 Row是一个类,它有一个属性 Values这是一个字典。

以下是 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");

如果“用户名”键不在字典中,则会发生这种情况。

我得到一个异常(exception),无效的类型转换:

出现以下错误:

System.InvalidCastException:指定的强制转换无效。
TryGetValue[T](Row row, String key, T defaultValue) 

TryGetValue[T](Row row, String key) 

所以我猜TryGetValue不适用于字符串?

最佳答案

是否有可能您的字典中有一个带有键“用户名”的条目,其值为 不是字符串 ?

我已经在您的方法中添加了注释,解释了这会如何导致您的问题。

// 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;
}

关于c# - C# 中的 TryGetValue 不适用于字符串,是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2930110/

相关文章:

c# - PayPal 即时付款通知 (IPN) 不工作 ASP.NET C#

c# - 从处理指令行读取 XML 属性

c# - 将用户控件从类型名称转换为自定义控件类型?

将结构指针转换为另一个结构

c# - 将 LINQ 与异步混合(从种子获取有效负载)

c# - 覆盖 machine.config 中的单个属性

c# - Windows 窗体在没有文本框的情况下添加文本

c++ - 至少有时将 uint8_t 转换为 signed int 是不正确的吗?

java - 如何动态确定 Object 类型文字的实际类型

Java Jung 类型转换和 getTrees()