首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#中使用接口作参数(新手有关问题)

2012-01-19 
C#中使用接口作参数(新手问题)usingSystemusingSystem.Collections.GenericusingSystem.TextnamespaceE

C#中使用接口作参数(新手问题)
using   System;
using   System.Collections.Generic;
using   System.Text;

namespace   Example10_8
{
        class   program
        {
                public   static   void   Main(string[]   args)
                {
                        Circle   circle   =   new   Circle(35);
                        MyClass   myClass   =   new   MyClass(circle);

                        Console.ReadLine();
                }
               
        }

        //ISshape接口
        interface   ISshape
        {
                //ISshape属性
                int   Area
                {
                        get;
                        set;
                }
                //ISshape方法
                void   Caculate();
        }
        //Circle类继承ISshape
        class   Circle   :   ISshape
        {
                //初始化字段
                int   area   =   0;

                //构造函数
                public   Circle(int   m_Area)
                {
                        area   =   m_Area;
                }

                #region   ISshape成员

                //Area属性
                public   int   Area
                {
                        get
                        {
                                return   area;
                        }
                        set
                        {
                                area   =   value;


                        }
                }
                //Caculate方法
                public   void   Caculate()
                {
                        Console.WriteLine( "计算面积 ");
                }
                #endregion
        }
        //MyClass类
        class   MyClass
        {
                public   MyClass(ISshape   shape)
                {
                        shape.Caculate();

                        Console.WriteLine(shape.Area);
                }
        }
}


/*
小弟最近正在苦读C#,看到了接口这儿,有点晕了
请问这段程序中的“35”这个值,是怎么传递过去的呢?
其实说白了,就是想请教一下大家这个接口到底是怎么个继承的关系哈!~
谢谢!
*/


[解决办法]
实际是把circle看做ISshape类型来处理的。

因为circle有Area属性,是从ISshape继承来的。
所以可以直接按ISshape 来处理;

接口就是一种约定,实现了接口,就是实现了这个接口的约定,也就一定有接口的成员,也就可以通过这个约定调用接口中有的成员。

热点排行