大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
接口把一组公共方法和属性组合起来 ,以封装特定功能的一个集合。通过类可以实现接口,这样类就支持接口所有的属性和方法。
接口只能对方法和属性进行定义,不能实现,只能由支持它的类实现。接口中的成员不能用访问符修饰,默认为public。
类必须为基类列表中列出的接口提供所有方法的实现。

using System;


namespace ConsoleApplication1
{
    
//声明接口,接口成员均为public,不能加权限修饰
    interface IF
    
{
        
//方法
        void Fun1();
        
void Fun2();

        
//属性
        int IntValue
        
{
            
get;
            
set;
        }


        
//索引指示器
        int this[int index]
        
{
            
set;
            
get;
        }

    }


    
//实现接口的类,从接口中实现的方法、属性必须是public
    class Impl : IF
    
{
        
//类的成员变量
        private int mi;
        
private int [] mArray;

        
//隐式实现接口成员,可以使用virtual,供派生类override
        virtual public void Fun1()
        
{
            Console.WriteLine(
"Implement Fun1");
        }


        
//显式实现接口成员,不能使用virtual,不能加权限修饰
        void IF.Fun2()
        
{
            Console.WriteLine(
"Implement Fun2");
        }


        
//实现接口中的属性
        public int IntValue
        
{
            
get return mi; }
            
set { mi = value; }
        }


        
//实现接口中的索引指示器
        public int this[int index]
        
{
            
set
            
{
                mArray[index] 
= value;
            }

            
get
            
{
                
return mArray[index];
            }

        }


    }


    
class DerivedImpl : Impl
    
{
        
//override基类隐式实现的接口成员
        public override void Fun1()
        
{
            Console.WriteLine(
"DerivedImpl Fun1");
        }

    }


    
class Program
    
{
        
static void Main(string[] args)
        
{
            
//通过接口调用方法
            IF i = new DerivedImpl();
            i.Fun1();
            i.Fun2();

            Impl ip 
= new Impl();
            ip.Fun1();
            
//error,显式实现的接口成员不能通过类调用,只能通过接口引用
            
//ip.Fun2();

        }

    }

}





posted on 2009-06-15 10:15 大胖 阅读(118) 评论(0)  编辑 收藏 引用 所属分类: C#

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理