简体   繁体   中英

Generics with Dictionary in c#

I want to return a dictionary but there are 2 types of keys that I can have so I want to include T in my return value. Any Ideas?

like so

public static Dictionary<string, T> Read<T>(string dicValueType, string path)
{ 

    if(dicValueType.Equals("User"))
    {
       Dictionary<string, User> usersDictionary = 
                   JsonConvert.DeserializeObject<Dictionary<string, User>> 
                                                     (File.ReadAllText(path));
       return usersDictionary;
    }
    Dictionary<string, Column> boardDictionary = 
                     JsonConvert.DeserializeObject<Dictionary<string, Column>> 
                                                (File.ReadAllText(path));
    return boardDictionary;
}

I'm getting an error in this line "return usersDictionary;"

Isn't all you want to deserialize a JSON object to generic. This will do it without all the if-else checks:

public static Dictionary<string, T> Read<T>(string path) 
    => JsonConvert.DeserializeObject<Dictionary<string, T>>(File.ReadAllText(path));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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