接口的实现

kj289907795 2010-10-13 11:28:48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace interfaceoo
{
interface myinterface
{
string STR
{
get;
set;
}
void outMethod();
}
class interfaceuse : myinterface
{
string str = "接口实现";
public string STR
{
get { return str; }
set { str = value; }
}
public void outMethod()
{
Console.WriteLine(this.STR);
}
}

class Program
{
static void Main(string[] args)
{
interfaceuse interfaceuser = new interfaceuse();
interfaceuser.outMethod();
}
}
}

上面是书的列子,看了并没有清楚接口作用, 请教各位大侠
...全文
80 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
kj289907795 2010-10-13
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace interfaceoo
{
interface D
{
string STR
{
get;
set;
}
void outMethod();
}
class A : D
{
string str = "接口实现";
public string STR
{
get { return str + "A"; }
set { str = value; }
}
public void outMethod()
{
if (Console.ReadLine().ToString() == "1")
Console.WriteLine(this.STR);
}
}
class B : D
{
string str = "接口实现";
public string STR
{
get { return str + "B"; }
set { str = value; }
}
public void outMethod()
{
if (Console.ReadLine().ToString() == "2")
Console.WriteLine(this.STR);
}
}
class C : D
{
string str = "接口实现";
public string STR
{
get { return str + "C"; }
set { str = value; }
}
public void outMethod()
{
if(Console.ReadLine().ToString() == "3")
Console.WriteLine(this.STR);
Console.Read();
}
}

class Program
{
static void Main(string[] args)
{
//''''''''''''''''''
// ''''''''''''''''''
// ''''''''''''''''''
// ''''''''''''''''''
}
}
}

按照2楼的思想,我改进了书上的列子,请各位大侠帮我实现一下
kj289907795 2010-10-13
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 pyjhlovemoon 的回复:]
用接口一种简单的情况 A,B,c 都继承一个d接口 都有个do方法,这样在后面的执行代码里 你都用这个接口的d.do方法 调用就可以了
最初你的需求是用A.do() D=A as d
后来你的需求变了 需要用 B.do()方法 这时你只要把最初的部份改成 D=B as d 就可以了 后面的执行代码都不需要改变
[/Quote]
可以写个简单的代码吗?
小童 2010-10-13
  • 打赏
  • 举报
回复
接口是一组规范,它要求实现了此接口的所有类都必须具有某些行为,也就是接口里面定义的方法,这些类都必须实现,
pyjhlovemoon 2010-10-13
  • 打赏
  • 举报
回复
用接口一种简单的情况 A,B,c 都继承一个d接口 都有个do方法,这样在后面的执行代码里 你都用这个接口的d.do方法 调用就可以了
最初你的需求是用A.do() D=A as d
后来你的需求变了 需要用 B.do()方法 这时你只要把最初的部份改成 D=B as d 就可以了 后面的执行代码都不需要改变
kj289907795 2010-10-13
  • 打赏
  • 举报
回复
对列子 做如下修改
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 写写吧
{
//interface myinterface
//{
// string STR
// {
// get;
// set;
// }
// void outMethod();
//}
//class interfaceuse : myinterface
class interfaceuse
{
string str = "接口实现";
public string STR
{
get { return str; }
set { str = value; }
}
public void outMethod()
{
Console.WriteLine(this.STR);
}
}

class Program
{
static void Main(string[] args)
{
interfaceuse interfaceuser = new interfaceuse();
interfaceuser.outMethod();
}
}
}

执行结果是一样 为什么要用接口呢?

110,567

社区成员

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

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

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