C# 返回值是接口的方法
今天写PIE二次开发加载栅格数据的时候发现类中方法的返回值是接口,之前没怎么写过,在此记录一下。
在例子中设计一个接口 ICalculate ,接口中有两个方法, Add() 和 Div() 分别为加法和减法的功能,均有两个参数,参数和返回值的类型都是int类型。
设计一个名为Calculate的类,继承ICalculate接口,类中实现了接口中的方法,没有增加新方法。
在Program类中写了一个CalTest()的静态方法,返回值为ICalculate类型,方法中实例化一个Calculate并且直接作为返回值,这里为什么可以作为返回值也可以理解,因为Calculate继承了并实现了ICalculate接口,所以可以通过父类(接口)来引用子类的对象,这也是面向对象的特点。
在Main方法中用ICalculate引用CalTest()方法,并调用接口中的方法。
描述可能不清楚,看代码,代码如下:
namespace _20200618接口再学习
{
class Program
{
static void Main(string[] args)
{
ICalculate test = CalTest();
int a = test.Add(3, 4);
Console.WriteLine(a);
Console.ReadKey();
}
static ICalculate CalTest()
{
Calculate calculate = new Calculate();
return calculate;
}
}
interface ICalculate
{
int Add(int x, int y);
int Div(int x, int y);
}
class Calculate : ICalculate
{
public int Add(int x, int y)
{
return x + y;
}
public int Div(int x, int y)
{
return x - y;
}
}
}其实总结是从别处看到的这两句话:
接口做为参数传递,传递的是实现了接口的对象;
接口作为类型返回,返回的是实现了接口的对象。



鲁公网安备 37148202000241号