C# Return Different Types?

后端 未结 15 2056
无人及你
无人及你 2020-12-08 09:11

I got something like this:

public [What Here?] GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = ne         


        
15条回答
  •  暖寄归人
    2020-12-08 09:59

    Defining a single type for all is not always possible. Even if when you can, the implementation is rarely easy. I prefer to use out parameters. The only caveat is that you need to know all the return types in advanced:

    public void GetAnything(out Hello h, out Computer c, out Radio r)
    {
         /// I suggest to:
         h = null;
         c = null;
         r = null; 
         // first, 
    
         // Then do whatever you have to do:
         Hello hello = new Hello();
         Computer computer = new Computer();
         Radio radio = new Radio();
    }
    

    The return type can be a void, or something else, like bool an int or a predefined enum which can help you check for exceptions or different cases wherever the method is used.

提交回复
热议问题