分享

c#接口作为返回类型怎么理解

 kittywei 2012-02-24
10.1.5  使用接口作为返回值
同10.1.4小节中使用接口作为参数一样,接口同样可以作为返回值,本小节同样通过一个实例演示接口的此种使用方法。

实例中定义了一个IShape接口,表示图形,另外定义了一个Circle类,表示圆形,并实现了IShape接口,在MyClass类中有一个MyOutput方法,该方法的返回值是IShape接口类型的,实例代码如下。

using System;

using System.Collections.Generic;

using System.Text;

namespace Example10_9

{

   class Program

   {

       static void Main(string[] args)

       {

           //创建Circle类变量circle,并使用其作为参数创建MyClass型变量myClass

           Circle circle = new Circle(35);

           MyClass myClass = new MyClass(circle);

           

           //获取返回值,并输出其面积Area属性

           Circle circle1 = (Circle)myClass.MyOutput(circle);

           Console.WriteLine(circle1.Area);

           Console.ReadLine();

       }

   }

   /// <summary>

   /// IShape接口

   /// </summary>

   interface IShape

   {

       /// <summary>

       /// Area属性

       /// </summary>

       int Area

       {

           get;

           set;

       }

       /// <summary>

       /// Caculate方法

       /// </summary>

       void Caculate();

   }

   /// <summary>

   /// Circle类继承IShape

   /// </summary>

   class Circle:IShape

   {

       /// <summary>

       /// area字段

       /// </summary>

       int area = 0;

       /// <summary>

       /// 构造函数

       /// </summary>

       /// <param name="m_Area">m_Area参数</param>

       public Circle(int m_Area)

       {

           area = m_Area;

       }

       #region IShape 成员

       /// <summary>

       /// Area属性

       /// </summary>

       public int Area

       {

           get

           {

               return area ;

           }

           set

           {

               area = value;

           }

       }

       /// <summary>

       /// Caculate方法

       /// </summary>

       public void Caculate()

       {

           Console.WriteLine("计算面积!");

       }

       #endregion

   }

   /// <summary>

   /// MyClass类

   /// </summary>

   class MyClass

   {

       /// <summary>

       /// 构造函数

       /// </summary>

       /// <param name="m_shape">IShape型参数</param>

       public MyClass(IShape m_shape)

       {

           m_shape.Caculate();

           Console.WriteLine(m_shape.Area);

       }

       /// <summary>

       /// MyOutput方法

       /// </summary>

       /// <param name="m_shape">IShape接口类型参数</param>

       /// <returns>IShape接口类型返回值</returns>

       public IShape MyOutput(IShape m_shape)

       {

           m_shape.Area = 100;

           return m_shape;

       }

   }

}

程序运行结果如下。

计算面积!

35

100

通过结果可以看到,程序中可以很方便的使用作为返回值类型的一种约束。不仅对返回值的类型进行了限定,还提供了一定的灵活性。即使程序进行了更新,比如添加了其他类型如正方形类,矩形类,只要这些类继承了IShape接口,即可方便的进行使用。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多