关于接口的一个小问题
// keyword_interface_2.cs
// Interface implementation
using System;
interface IPoint
{
// Property signatures:
int x
{
get;
set;
}
int y
{
get;
set;
}
}
class Point : IPoint
{
// Fields:
private int _x;
private int _y;
// Constructor:
public Point(int x, int y)
{
_x = x;
_y = y;
}
// Property implementation:
public int x
{
get
{
return _x;
}
set
{
_x = value;
}
}
public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}
class MainClass
{
static void PrintPoint(IPoint p)
{
Console.WriteLine( "x={0}, y={1} ", p.x, p.y);
}
static void Main()
{
Point p = new Point(2, 3);
Console.Write( "My Point: ");
PrintPoint(p);
}
}
在构造PrintPoint()方法时为什么使用的是接口的对象作为参数。接口不是不能实例化的么?那为什么能够用它来作为方法的参数呢?
[解决办法]
他将接口作为参数不是不对,虽然接口不能实例化,但是 继承了接口的类 实例化后,把类赋值给接口变量,这样就可以调用了。
比如:
interface IPoint
{
// Property signatures:
int x
{
get;
set;
}
int y
{
get;
set;
}
}
这是声明了一个接口
class Point : IPoint
{
// Fields:
private int _x;
private int _y;
// Constructor:
public Point(int x, int y)
{
_x = x;
_y = y;
}
// Property implementation:
public int x
{
get
{
return _x;
}
set
{
_x = value;
}
}
public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}
上面是继承接口的类,并实现了接口。
假如我实例化Point类:
Point p=new Point(1,2);
我再声明一个IPoint接口,
IPoint Ip;
把类赋值给接口,Ip=p;
这样就可以Ip.x Ip.y这样调用了。
这样操作方便,可以不与类的其他成员混淆。
[解决办法]
你后来提问的问题,就你这个例子来说,应该没什么区别,如果Point类中还有别的成员,你传入IPoint只能访问x y两个属性,而传入Point类则全部都能访问。
这也是接口的方便之一。
[解决办法]
有区别
IPoint p,这样对P的操作只能基于IPoint所有的成员方法
Point p,这样对P的操作是基于Point所有的成员方法
关键在于IPoint和Point之间的区别,如果Point仅仅实现了IPoint接口,那么可以这两种方式的结果是一样的,但如果Point有另外定义的成员方法属性,那么用Point P显然可以进行比IPoint更多的操作。
通常实践中使用IPoint P这样的方式,是为了限定对基类的操作,以保证该过程的通用性。