简单问题,类的继承,接口的继承。

terry915 2008-04-02 05:37:37
using System;

public class Student
{
private IAdviser adviser;
public void SetAdviser(IAdviser iadviser)
{
adviser = iadviser;
}
private int score;
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (adviser != null)
{
string result = adviser.Advise(score);
Console.Out.WriteLine("学生收到老师返回的结果\t"+result);
}
}
}
}

public interface IAdviser

{
string Advise(int score);
}

public class Teacher : IAdviser
{
public string Advise(int score)
{
if (score < 60)
{
Console.Out.WriteLine(score+"老师说加油");
return "不及格";
}
else
{
Console.Out.WriteLine(score+"老师说不错");
return "及格";
}
}
}

class MainClass
{
[STAThread]
private static void Main(string[] args)
{
IAdviser teacher = new Teacher();
Student s = new Student();
....
}
}

在代码的倒数第五行中,为什么要用
IAdviser teacher = new Teacher();
而不是
Teacher teacher = new Teacher();
有什么差别?
为什么两种都不会出错呢?
...全文
100 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yunfeng007 2008-04-03
  • 打赏
  • 举报
回复
接口(interface)用来定义一种程序的协定。实现接口的类或者结构要与接口的定义严格一致。
将你的程序做一下修改可能看的比较清楚

public interface IAdviser

{
string Advise(int score);
}

public class Teacher : IAdviser
{
public string Advise(int score)
{
if (score < 60)
{
Console.Out.WriteLine(score+"老师说加油");
return "不及格";
}
else
{
Console.Out.WriteLine(score+"老师说不错");
return "及格";
}
}
}

public class OtherTeacher : IAdviser
{
public string Advise(int score)
{
Console.Out.WriteLine(score+"老师说:我就判你不及格,您能把我怎么着!");
return "不及格";
}
}
class MainClass
{
[STAThread]
private static void Main(string[] args)
{
//IAdviser teacher = new Teacher();
IAdviser teacher = new OtherTeacher();//在此做替换
Student s = new Student();


....
}
}

refeiner 2008-04-03
  • 打赏
  • 举报
回复
提供一个一致性的访问通道
这个意思大体为:接口定义了什么功能,我直接去接口里面找,而不管他的具体实现
设计模式问题
skynice 2008-04-03
  • 打赏
  • 举报
回复
面向结口编程的原则。
看看设计模式吧
priwilliam 2008-04-02
  • 打赏
  • 举报
回复
用接口来实现多继承 只不过您的接口只有一个
JYYCOM 2008-04-02
  • 打赏
  • 举报
回复
其实接口只是一种规则
假如:
public class Teacher : IAdviser IASK

IAdviser teacher = new Teacher(); 声明的teacher中只有IAdviser中定义的方法。
而 IASK teacher=new Teacher();中的teacher只有IASK中的方法。
一个类可以实现多个接口。

terry915 2008-04-02
  • 打赏
  • 举报
回复
后面的代码如下:
class Program
{
[STAThread]
private static void Main(string[] args)
{
IAdviser teacher = new Teacher();
Student s = new Student();
s.SetAdviser(teacher);
Console.WriteLine("学生得到50分");
s.SetScore(50);
Console.WriteLine("\n学生得到75分");
s.SetScore(75);
Console.ReadLine();
}
}

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧