C# Return Different Types?

后端 未结 15 2046
无人及你
无人及你 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:53

    To build on the answer by @RQDQ using generics, you can combine this with Func (or some variation) and delegate responsibility to the caller:

    public T GetAnything(Func createInstanceOfT)
    {
        //do whatever
    
        return createInstanceOfT();
    }
    

    Then you can do something like:

    Computer comp = GetAnything(() => new Computer());
    Radio rad = GetAnything(() => new Radio());
    

提交回复
热议问题