// 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 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()方法时为什么使用的是接口的对象作为参数。接口不是不能实例化的么?那为什么能够用它来作为方法的参数呢?
{
Console.WriteLine("x={0}, y={1}", p.x, p.y);
}
那是不是可以把PrintPoint方法的参数改为(Point p)来定义,这样和上面的定义有区别么?
比如:
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这样调用了。
这样操作方便,可以不与类的其他成员混淆。
这也是接口的方便之一。