C# Return Different Types?

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

    It's a sample using Generic Types.

    public T GetAnything() where T : class, new()
        => new T();
    

    And you'll use this method calling this way:

    var hello = GetAnything();
    

    In this case, you can use an interface to specify a type to pass as parameter.

    public T GetAnything() where T : ISomeInterface, new()
        => new T();
    

    You must have a parameterless construtor in each class to use new() constraint.

    Follow the full sample:

    internal sealed class Program
    {
        private static void Main(string[] args)
        {
            GetAnything().Play();
            GetAnything().Play();
            GetAnything().Play();
        }
    
        private static T GetAnything() where T : ISomeInterface, new()
            => new T();
    }
    
    internal interface ISomeInterface
    {
        void Play();
    }
    
    internal sealed class Hello : ISomeInterface
    {
        // parameterless constructor.
        public Hello() { }
        public void Play() => Console.WriteLine("Saying hello!");
    }
    
    internal sealed class Radio : ISomeInterface
    {
        // parameterless constructor.
        public Radio() { }
        public void Play() => Console.WriteLine("Playing radio!");
    }
    
    internal sealed class Computer : ISomeInterface
    {
        // parameterless constructor.
        public Computer() { }
        public void Play() => Console.WriteLine("Playing from computer!");
    }
    

提交回复
热议问题