简体   繁体   English

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

[英]Return generic type from dictionary (else return a default generic value)

I'm trying to pass a key to a dictionary (of objects) and get the value out (which could be various types) or fallback to a default value I supplied. 我正在尝试将密钥传递给(对象的)字典并获取值(可能是各种类型),或回退到我提供的默认值。

For example 例如

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

Firstly I was getting. 首先,我得到了。 Cannot implicitly convert type object to T. An explicit conversion exists (are you missing a cast?) 无法将类型对象隐式转换为T。存在显式转换(是否缺少强制类型转换?)

So I cast the key return with 所以我用

return (T)settingsDictionary[key];

This got rid of the compile error but I have InvalidCastExpections. 这摆脱了编译错误,但我有InvalidCastExpections。 For instance in the json numbers are stored as 35.0 (which would be a double) and if I call: 例如在json中,数字存储为35.0(将是双精度数字),如果我调用:

GetValueFromSettings("someOffset", 32.0f);

I'll get an InvalidCastExpection when it finds the key in the json as 32.0 and tries to convert to a float. 当它在json中找到键为32.0并尝试转换为浮点数时,我将获得InvalidCastExpection。

I also tried using a generic instead of object: 我也尝试使用泛型而不是对象:

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

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

    return defaultValue;
}   

In the hope that it would fix it but that also results in an invalid cast exception. 希望它可以解决它,但也导致无效的强制转换异常。 This time it's on the dictionary though as the json expects a type of Dictionary. 这次是在字典上,尽管json期望使用字典的类型。

I've also seen System.Convert.ChangeType() but again no luck. 我也看到了System.Convert.ChangeType(),但是再没有运气了。

Any help would be appreciated. 任何帮助,将不胜感激。

What you're seeing (in the first case) is that you can't unbox from int to float . 您所看到的(在第一种情况下)是您无法从int取消装箱到float What you're seeing when casting the dictionary itself is that a Dictionary<string, object> isn't a Dictionary<string, float> , which seems entirely reasonable to me. 在转换字典本身时,您看到的是Dictionary<string, object>不是Dictionary<string, float> ,对我来说这完全合理。

You might want to use: 您可能要使用:

// I don't *expect* that you need a cast herem, given the type argument
var settingsDictionary = ParseConfig.CurrentConfig.Get<Dictionary<string, object>>("settings");
object value;
if (!settingsDictionary.TryGetValue(key, out value))
{
    return defaultValue;
}
object converted = Convert.ChangeType(value, typeof(T));
return (T) converted;

That will handle far more conversions - but it will throw an exception if there's no suitable conversion available. 这将处理更多的转化-但是,如果没有合适的转化可用,它将引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM