小编use*_*934的帖子

从字典返回泛型类型(否则返回默认泛型值)

我试图将键传递给(对象的)字典并获取值(可能是各种类型)或回退到我提供的默认值。

例如

// Called from some other method
// It should look in the dictionary for that key and return the value
// else return the int 365
GetValueFromSetting("numDaysInYear", 365)

public static T GetValueFromSettings<T>(string key, T defaultValue)
{
    // Settings is a dictionary, which I get in json form
    Dictionary<string, object> settingsDictionary = (Dictionary<string, object>)ParseConfig.CurrentConfig.Get<Dictionary<string, object>>("settings");

    if(settingsDictionary.ContainsKey(key))
    {
        return settingsDictionary[key];
    }

    return defaultValue;
}   
Run Code Online (Sandbox Code Playgroud)

首先我得到了。无法将类型对象隐式转换为 T。存在显式转换(是否缺少强制转换?)

所以我用回车键

return (T)settingsDictionary[key];
Run Code Online (Sandbox Code Playgroud)

这消除了编译错误,但我有 InvalidCastExpections。例如,在 json 中,数字存储为 35.0 (这将是一个双精度),如果我调用:

GetValueFromSettings("someOffset", 32.0f);
Run Code Online (Sandbox Code Playgroud)

当它发现 json 中的键为 …

c# generics json dictionary

1
推荐指数
1
解决办法
1308
查看次数

标签 统计

c# ×1

dictionary ×1

generics ×1

json ×1