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

前端 未结 6 1654
悲哀的现实
悲哀的现实 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:24

    Why not have a base class that has Output defined. Then return the base.

    public abstract class BaseType {
        public abstract void Output();
    }
    

    Both Articles and Questionaire should inherit this BaseType.

    public class Articles : BaseType {
      // Output method here
    }
    
    public class Questionaire : BaseType {
     // Output method here
    }
    

    Then you can do:

    public static BaseType Choose(int x, string name) 
    {
        if (x == 1)
        {
           Articles art = new Articles(name);
           return art;
        }
        if (x == 2)
        {
            Questionnaire ques = new Questionnaire(name);
            return ques;
        }
    }
    

    You could also achieve this via an interface.

    public interface IInterface {
        void Output();
    }
    
    public class Articles : IInterface {
      // Output method here
    }
    
    public class Questionaire : IInterface {
     // Output method here
    }
    

    You would then have to modify the Choose method to return IInterface rather than BaseType. Whichever you choose is up to you.

    Note: even if you can't change original classes you can still use these approaches before resorting to dynamic by providing wrapper classes that implement the interface and either inherits original or forwards calls to corresponding method:

    public class ArticlesProxy : Articles, IInterface 
    {
      public ArticlesProxy(string name) : base(name){}
    
    }
    
    public class QuestionaireProxy : Questionaire, IInterface {
      Questionaire inner;
      public QuestionaireProxy(string name) {  inner = new Questionaire(name); }
    
      public void Output() { inner.Output();}
    
    }
    

提交回复
热议问题