Method with Multiple Return Types

前端 未结 3 1050
梦如初夏
梦如初夏 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:15

    The return type of a function must be typed. As with any other variable or operation, any type that inherits from the specified type is a valid return value (which is why object allows anything as a value).

    Personally i dont think it is useful to make one method with multiple return types but if you really want to have one method with multiple return types, you could use the dynamic type in .NET 4.0:

        private static void Main(string[] args)
        {
            int x = Method("varName3");
            string word = Method("varName2");
            bool isTrue = Method("varName1");
        }
    
        private static dynamic Method(string key)
        {
            var dictionary = new Dictionary<string, KeyValuePair<Type, object>>()
            {
                { "varName1", new KeyValuePair<Type, object>(typeof(bool), false) },
                { "varName2", new KeyValuePair<Type, object>(typeof(string), "str") },
                { "varName3", new KeyValuePair<Type, object>(typeof(int), 5) },
            };
    
            if (dictionary.ContainsKey(key))
            {
                return dictionary[key].Value;
            }
    
            return null;
        }
    

    Hope it helps

    0 讨论(0)
  • 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<T>(string key)
    {
        if(dictionary.ContainsKey(key))
            return (T) Convert.ChangeType(dictionary[key].Value, typeof(T));
        return default(T);
    }
    
    ...
    
    int x = Method<int>(key);
    string word = Method<string>(key);
    bool isTrue = Method<bool>(key);
    

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

    0 讨论(0)
  • 2021-02-14 08:23

    In C# 7 you have the option to return multiple values from a method like this:

    public (string SomeString, int SomeInt) DoSomething() {... }
    

    You can get the values like this:

    var result = DoSomething();
    Console.WriteLine(result.SomeString);
    Console.WriteLine(result.SomeInt.ToString());
    

    Or

    (var someString, var someInt) = DoSomething();
    Console.WriteLine(someString);
    Console.WriteLine(someInt.ToString());
    

    This works below the surface with a Tuple and you are not restricted to only 2 values. I don't know how many you can return but I suggest when you need to return that many values, create a class. More info: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

    0 讨论(0)
提交回复
热议问题