返回不同类型的两种可能的对象中的一个共享的方法两种、不同类型、象中、方法

2023-09-03 00:22:03 作者:笙兮。

我有2类:

public class Articles
{
    private string name;

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

    public void Output()
    {
        Console.WriteLine("The class is: " + this.GetType());
        Console.WriteLine("The name is: " + name);
    }
}

public class Questionnaire 
{
    private string name;

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

    public void Output()
    {
        Console.WriteLine("The class is: " + this.GetType());
        Console.WriteLine("The name is: " + name);
    }
}

我想写一个方法,即取一个整数(1含义文章应归还,2含义问卷)和一个名称。

I want to write a method, that takes an integer (1 meaning Articles should be returned, 2 meaning Questionnaire) and a name.

此方法必须返回这两个类中的一个实例:

This method must return an instance of one of those two classes:

public [What type??] 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;
        }
    }

我应该使用什么样的返回类型,这样我就可以叫输出()的结果?

推荐答案

为什么不能有一个的基类具有输出定义。然后返回基地。

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

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

两个文章问卷应该继承这个 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
}

您将不得不修改选择方法返回 IInterface ,而不是 BASETYPE 。无论你的选择是由你。

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();}

}