C# Return Different Types?

后端 未结 15 2086
无人及你
无人及你 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 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(); 
    

提交回复
热议问题