explicit(显)
implicit(隐)
class Celsius
{
public float degree;
public Celsius(float _d)
{
degree = _d;
}
public static explicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit(c.degree * 9);
}
}
class Fahrenheit
{
public float degree;
public Fahrenheit(float _d)
{
degree = _d;
}
public static explicit operator Celsius(Fahrenheit f)
{
return new Celsius(f.degree / 4);
}
}
class Program
{
static void Main(string[] args)
{
Celsius c = new Celsius(16);
Fahrenheit f = (Fahrenheit)c;
c = (Celsius)f;
// Fahrenheit f = c;
// c = f;
Console.WriteLine(c.degree);
Console.ReadLine();
}
}
static:
不用实例化对象就可以使用。
abstract :
1.不可以实例化。
2.默认是virtual 所以不可以申明是virtual或者static。
3.不可以是sealed,因为 sealed不可以被继承。
interface 设计
1.默认public,所以函数不用再申明public。
2.类单继承但是可以很多interface 。
interface Paint
{
void print(int type); //no public
}
class plainPaint : Paint
{
public void print(int type)
{
Console.WriteLine("printing from a plain text editor");
}
}
class GuiPaint: Paint
{
public void print(int type)
{
Console.WriteLine("printing from a gui editor"); //different realization
}
}
class Program
{
static void print (plainPaint e,int type) //a good way to call print()
{
e.print(type);
}
static void Main(string[] args)
{
plainPaint i = new plainPaint();
print(i, 2);
i.print(2);
Console.ReadLine();
}
}
继承多个interface 的方法一致,但不同实现,就像你的角色有女儿舍友等等,面对不同人的不同反应。
interface EnglishShape
{
float getWidth();
float getHeight();
}
interface MetricShape
{
float getWidth();
float getHeight();
}
class Box : EnglishShape, MetricShape
{
private float width, height;
public Box(float w,float h)
{
width = w;
height = h;
}
float MetricShape.getHeight()
{
return height * 2.54f;
}
float EnglishShape.getHeight()
{
return height;
}
float MetricShape.getWidth()
{
return width * 2.54f;
}
float EnglishShape.getWidth()
{
return width;
}
}
class Program
{
static void Main(string[] args)
{
Box box = new Box(1, 2);
EnglishShape enbox = (EnglishShape)box;
Console.WriteLine(enbox.getHeight());
MetricShape metribox = (MetricShape)box;
Console.WriteLine(metribox.getHeight());
Console.ReadLine();
}
}
get set方法可以保护变量,控制他的访问和读写权,以及写入的可行性。
但是get set只能比(比如这里 AmoutOfWheels)更加保守。
class Vehicle
{
private int amoutOfWheels;
public int AmoutOfWheels
{
get //can protect the amountOfWheels from being read by deletinf it;
{
return amoutOfWheels;
}
set //can protect the am.. from being written;
{
if(value > 0) //can prevent the stupid program to assign a negative value to ammout...;
amoutOfWheels = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Vehicle v = new Vehicle();
v.AmoutOfWheels = 4;
v.AmoutOfWheels = -9; //useless;
Console.WriteLine(v.AmoutOfWheels);
Console.ReadLine();
}
}