C# Return Different Types?

后端 未结 15 2044
无人及你
无人及你 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.

    0 讨论(0)
  • 2020-12-08 10:00

    If you can make a abstract class for all the possibilities then that is highly recommended:

    public Hardware GetAnything()
    {
         Computer computer = new Computer();
    
         return computer;    
    }
    
    abstract Hardware {
    
    }
    
    class Computer : Hardware {
    
    }
    

    Or an interface:

    interface IHardware {
    
    }
    
    class Computer : IHardware {
    
    }
    

    If it can be anything then you could consider using "object" as your return type, because every class derives from object.

    public object GetAnything()
    {
         Hello hello = new Hello();
    
         return hello;    
    }
    
    0 讨论(0)
  • 2020-12-08 10:04

    You can have the return type to be a superclass of the three classes (either defined by you or just use object). Then you can return any one of those objects, but you will need to cast it back to the correct type when getting the result. Like:

    public object GetAnything()
    {
         Hello hello = new Hello();
         Computer computer = new Computer();
         Radio radio = new Radio();
    
         return radio; or return computer; or return hello //should be possible?!      
    }
    

    Then:

    Hello hello = (Hello)getAnything(); 
    
    0 讨论(0)
提交回复
热议问题