码迷,mamicode.com
首页 > 其他好文 > 详细

The forth Assignment

时间:2015-04-06 16:54:56      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

1.Struct。。。。

这个几乎被遗忘的结构体。。我们就把他遗忘掉吧。。。

2.Interface。。

接口,使用interface关键字进行声明,功能是把所需成员组合起来,以封装一定功能的集合。它好比一个模板,在其中定义了对象必须实现的成员,通过类或结构来实现它。

接口不能直接实例化,接口不能包含成员的任何代码,只定义成员本身。接口成员的具体代码由实现接口的类提供。

public interface IStorable
{
  void Read( );      //前面没有access-modifier,后面没有方法的实现。
  void Write(object);
}
public class Document : IStorable
{
  public void Read( ) {...}    //方法的实现由继承接口的类来完成
  public void Write(object obj) {...}
}

接口可以继承接口来实现接口的拓展

interface ICompressible
{
  void Compress();
  void Decompress();
}
interface ILoggedCompressible : ICompressible
{
  void LogSavedBytes();
}

这样ILoggedCompressible这个接口就拥有了3个method。。。

但是当一个类继承这个接口的时候就需要实现3个method

public class Document : ILoggedCompressible 
{
  public void Compress(){ …}
  public void Decompress() { …}

  public void LogSavedBytes() { …}
}

 

一个类可以继承多个接口但只能继承一个基类。。。

public interface IStorable
{
  void Read( );
  void Write(object);
}
interface ICompressible
{
  void Compress();
  void Decompress();
}
public class Document : IStorable, ICompressible
{
  //实现IStorable
  public void Read( ) {...}
  public void Write(object obj) {...}
  // 实现ICompressible
  public void Compress(){ …}
  public void Decompress() { …}
}

 

 as Operator。。有点像强制类型转换()

技术分享

 技术分享

Document,IStorable,BigDocument,LittleDocument类的关系如上。

Document [] folder  = new Document[5];
for (int i = 0; i < 5; i++)
{
  if (i % 2 == 0)
  {
    folder[i] = new BigDocument("Big Document # " + i);
  }
  else
  {
    folder[i] = new LittleDocument("Little Document # " + i);
  }
}
foreach (Document doc in folder)
{
  IStorable isDoc = doc as IStorable;
  if (isDoc != null)
  {
    isDoc.Read();
  }else{
    Console.WriteLine("IStorable not supported");doc.Encrypt();
  }
}

在调用folder中元素的.Read()时需要使用as将doc转化成IStorable类。

如果as转化失败会返回一个null指针。

 

interface IStorable
{
  void Read();
  void Write();
}
interface ITalk
{
  void Talk();
  void Read();
}
public class Document : IStorable, ITalk
{
  public Document(string s){…; }
  // Make read virtual
  public void Read(){…; }    //IStorable的Read方法的隐式实现
  public void Write(){…; }
  void ITalk.Read(){ …; }    //ITalk的Read方法的显式实现
  public void Talk(){ …; } }

默认为隐式定义,显示定义前不加访问修饰符如public,private。

在调用时默认调用的是隐式定义的method,若将类转为显式实现对应的类时调用显式定义的method

Document theDoc = new Document(“Test”);
theDoc.Read();    //调用隐式定义的Read
ITalk itDoc = theDoc;
itDoc.Read();    //调用显式定义的Read

 

The forth Assignment

标签:

原文地址:http://www.cnblogs.com/tiny-home/p/4396044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!