如何使用IPrintable接口

本文关键字:接口 IPrintable 何使用 | 更新日期: 2023-09-27 18:22:17

我在IPrintable接口方面遇到了一些问题。

我有一个类Student类,它继承自Person类+studentID和类Person(name,lastname)。我必须编写一个IPrintable with Print()过程。Print()应该打印出Person或Student类中的每个字段。接下来我必须创建4个对象。

  1. 类对象分配给Person类型变量的Person
  2. 类对象分配给Person类型变量的学生
  3. 类对象Student分配给类型为Student的变量
  4. 类对象Student被分配到类型为IPrintable的变量

接下来,我必须创建IPrintable对象的列表,并将所有创建的对象添加到该列表中,然后使用print()方法循环打印该对象。

有人能帮我写代码吗?或者给我看一篇关于这个界面的文章?

//编辑

谢谢。我仍然对两件事感到困惑。这是我的代码:

个人.cs

class Person : IPrintable
{
    public string FirstName;
    public string LastName;
    public Person(string FirstName, string LastName)
    {
        this.FirstName = FirstName;
        this.LastName = LastName;
    }
    public override string ToString()
    {
        return this.FirstName + " " + this.LastName;
    }

}

学生.cs

class Student : Person
{
    public int ID;
    public Student(string FirstName, string LastName, int ID) : base(FirstName, LastName)
    {
        this.ID = ID;
    }
    public override string ToString()
    {
        return base.ToString() + " [" + this.ID + "]";
    }
}

程序.cs

class Program
{
    static void Main(string[] args)
    {
        Person o = new Student("John", "Smith", 231312); 
        Console.Write(o.ToString());
        return;
    }
}

我还有IPrintable.cs

interface IPrintable
{
    void Print();
}

我应该把Print()函数放在哪里,以便从Person和Student类访问它?我不知道如何使"Class对象Student分配给类型为IPrintable的变量"。

我认为这将是类似于:

IPrintable x = new Student("x", "x", 2231); 

但是如何让它发挥作用呢?

如何使用IPrintable接口

IPrintable不是C#中包含的接口;你应该自己做。它看起来是这样的:

public interface IPrintable {
    void Print();
}

因此,您应该了解接口的一般情况,让类实现接口的后果,以及多态性(将对象引用分配给更通用类型的变量)。

回答您的编辑:正如编译器可能告诉您的那样,Person必须包含一个public void Print()方法,因为该类实现了IPrintableStudent不必有一个,因为它继承了Person中的一个,但如果您希望以不同的方式打印Student,则需要使用public override void Print()覆盖该方法。

事实上,您的最后一个代码片段正是他们所要求的。它好像不起作用怎么办?

另外:请仔细阅读我提到的话题。不要仅仅对编译器接受IPrintable x = new Student("x", "x", 2231);感到满意,还要努力理解实际发生了什么(这一行做了三件不同的事情:实例化一个新的Student对象,创建一个新IPrintable变量,然后将对象分配给变量),为什么这样做是合法的,与做Person x = new Student("x", "x", 2231);有什么区别,以及为什么这样做Student x = new Person("x", "x");不合法。这里涉及的所有规则背后都有坚实的逻辑,但遗憾的是,很多老师都掩盖了这一点,只关注语法(同时把太多的语法强加给学生…)