C# Return Different Types?

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

    You have a few options depending on why you want to return different types.

    a) You can just return an object, and the caller can cast it (possibly after type checks) to what they want. This means of course, that you lose a lot of the advantages of static typing.

    b) If the types returned all have a 'requirement' in common, you might be able to use generics with constriants.

    c) Create a common interface between all of the possible return types and then return the interface.

    d) Switch to F# and use pattern matching and discriminated unions. (Sorry, slightly tongue in check there!)

提交回复
热议问题