对象 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/