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();
有什么差别?
为什么两种都不会出错呢?
{
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();
有什么差别?
为什么两种都不会出错呢?
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();
}
}
假如:
public class Teacher : IAdviser IASKIAdviser teacher = new Teacher(); 声明的teacher中只有IAdviser中定义的方法。
而 IASK teacher=new Teacher();中的teacher只有IASK中的方法。
一个类可以实现多个接口。
将你的程序做一下修改可能看的比较清楚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();
....
}
}