C#接口-接口作为返回值

接口做为参数传递,传递的是实现了接口的对象;

接口作为类型返回,返回的是实现了接口的对象。

using System;

// IShape接口

public interface IShape

{

// Area属性

int Area

{

get;

set;

}

// Caculate计算方法

void Caculate();

}

// Circle类继承IShape

public class Circle: IShape

{

// area字段

int area = 0;

// 构造函数

public Circle(int m_Area)

{

area = m_Area;

}

// Area属性

public int Area

{

get

{

return area;

}

set

{

area = value;

}

}

// Caculate方法

public void Caculate()

{

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

}

}

// MyClass类

public class MyClass

{

// 构造函数

public MyClass(IShape shape)

{

shape.Caculate();

Console.WriteLine(shape.Area);

}

}

class Program

{

static void Main(string[]args)

{

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

Circle cir = new Circle(35);

MyClass myClass = new MyClass(cir);

Console.ReadLine();

}

}