Method with Multiple Return Types

前端 未结 3 1059
梦如初夏
梦如初夏 2021-02-14 07:57

I\'ve looked through many questions that are similar to this, but none of them really touched on what I precisely want to do. What I am trying to do is read from an external sou

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-14 08:17

    The compiler has no way to distinguish between the three method calls you've provided, because they all look like Method(key);

    One option is to return an object and then expect the consuming code to cast it to what they want:

    public object Method(string key)
    {
        if(dictionary.ContainsKey(key))
        {
            var temp = dictionary[key];
    
            switch (temp.Type)
            {
                case "bool":
                    return Convert.ToBoolean(temp.Value);
    
                case "int"
                    return Convert.ToInt(temp.Value);
    
                case "string"
                    return temp.Value;
            }
        }
    
        return "NULL"; 
    }
    
    ...
    
    int x = (int) Method(key);
    string word = (string) Method(key);
    bool isTrue = (bool) Method(key);
    

    You could also use the dynamic keyword to make the cast implicit:

    public dynamic Method(string key)
    {
        if(dictionary.ContainsKey(key))
        {
            var temp = dictionary[key];
    
            switch (temp.Type)
            {
                case "bool":
                    return Convert.ToBoolean(temp.Value);
    
                case "int"
                    return Convert.ToInt(temp.Value);
    
                case "string"
                    return temp.Value;
            }
        }
    
        return "NULL"; 
    }
    
    ...
    
    int x = Method(key);
    string word = Method(key);
    bool isTrue = Method(key);
    

    However, dynamic is a very powerful concept, and it's easy for it to get out of hand, so you have to be really careful with that.

    It seems to me that you're expecting your calling code to know which type of object it's expecting to get for each key. It seems like maybe the best approach is to just let the user supply that information:

    public T Method(string key)
    {
        if(dictionary.ContainsKey(key))
            return (T) Convert.ChangeType(dictionary[key].Value, typeof(T));
        return default(T);
    }
    
    ...
    
    int x = Method(key);
    string word = Method(key);
    bool isTrue = Method(key);
    

    That way, there's no need to track the Type value in your dictionary objects in the first place.

提交回复
热议问题