Return one of two possible objects of different types sharing a method

前端 未结 6 1653
悲哀的现实
悲哀的现实 2020-12-06 05:12

I have 2 classes:

public class Articles
{
    private string name;

    public Articles(string name)
    {
        this.name = name;
    }

    public void O         


        
6条回答
  •  生来不讨喜
    2020-12-06 05:25

    How about something like this:

    public interface IHasOutput
    {
        void Output();
    }
    
    public class Articles : IHasOutput
    
    public class Questionnaire : IHasOutput
    

    and then:

    public static IHasOutput Choose...
    

    You can of course call your interface anything you'd like, other than IHasOutput, I just don't know what to call it. This is what interfaces are for. Two different concrete implementations that share a common interface. Now when you call it you can do this:

    var entity = MyClass.Choose(1, "MyName");
    entity.Output();
    

    and it doesn't matter what concrete implementation is returned. You know it implements a common interface.

提交回复
热议问题