C# Return Different Types?

后端 未结 15 2077
无人及你
无人及你 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: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;    
    }
    

提交回复
热议问题