接口的使用1

本文介绍在C#中如何使用接口作为参数传递及作为方法的返回值。通过具体的示例代码展示了如何定义接口、实现接口的类,并在另一个类中使用这些接口进行实例化和调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.使用接口作为参数

示例代码
1 using System;
2  using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace 接口作为参数
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 Circle circle = new Circle(35);
13 MyClass myclass = new MyClass(circle);
14 Console.ReadLine();
15 }
16 }
17
18 interface IShape
19 {
20 /// <summary>
21 /// Area属性
22 /// </summary>
23 int Area
24 {
25 get;
26 set;
27 }
28 void Caculate();
29 }
30 class Circle : IShape
31 {
32 /// <summary>
33 /// area字段
34 /// </summary>
35 int area = 0;
36
37 public Circle(int m_Area)
38 {
39 area = m_Area;
40 }
41
42 #region ISshape成员
43 public int Area
44 {
45 get
46 {
47 return area;
48 }
49 set
50 {
51 area = value;
52 }
53 }
54
55 public void Caculate()
56 {
57 Console.WriteLine("计算面积!");
58 }
59 #endregion
60 }
61 class MyClass
62 {
63 /// <summary>
64 /// 构造函数
65 /// </summary>
66 /// <param name="shape">IShape型参数</param>
67 public MyClass(IShape shape)
68 {
69 shape.Caculate();
70 Console.WriteLine(shape.Area);
71
72 }
73 }
74
75
76 }
77

 

2.使用接口作为返回值

转载于:https://www.cnblogs.com/zzw2011/archive/2010/12/21/1912318.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值