请问下面程序的运行结果是什么,会是矩形#3 高=10,宽=15么?如果是的话,那实例Console.WriteLine("矩形#3 " + objRect3);为什么会调用到 ToString()啊?
还有,Width,Height他们如果不用get、set来描述的话,好象程序运行也没什么问题,那这里get\set 有什么实际的意义么?
class Rectangle
{
private int iHeight;
private int iWidth; // 构造函数重载
public Rectangle(int w,int h)
{
Width=w;
Height=h;
} // 属性:宽 的get和set访问器
public int Width
{
get
{
return iWidth;
}
set
{
iWidth=value;
}
} // 属性:高 的get和set访问器
public int Height
{
get
{
return iHeight;
}
set
{
iHeight=value;
}
} // 属性:面积 的get访问器
public int Area
{
get
{
return Height*Width;
}
} // 重载操作符 ==
public static bool operator==(Rectangle a,Rectangle b)
{
return ((a.Height==b.Height)&&(a.Width==b.Width));
} // 重载操作符 !=
public static bool operator!=(Rectangle a,Rectangle b)
{
return !(a==b);
} // 重载操作符 >
public static bool operator>(Rectangle a,Rectangle b)
{
return a.Area>b.Area;
}
// 重载ToString
public override String ToString()
{
return "高=" + Height + ",宽=" + Width;
} public static void Main()
{
// 实例化矩形并设置各自属性
Rectangle objRect3 =new Rectangle(10,15);
Console.WriteLine("矩形#3 " + objRect3);
}
还有,Width,Height他们如果不用get、set来描述的话,好象程序运行也没什么问题,那这里get\set 有什么实际的意义么?
class Rectangle
{
private int iHeight;
private int iWidth; // 构造函数重载
public Rectangle(int w,int h)
{
Width=w;
Height=h;
} // 属性:宽 的get和set访问器
public int Width
{
get
{
return iWidth;
}
set
{
iWidth=value;
}
} // 属性:高 的get和set访问器
public int Height
{
get
{
return iHeight;
}
set
{
iHeight=value;
}
} // 属性:面积 的get访问器
public int Area
{
get
{
return Height*Width;
}
} // 重载操作符 ==
public static bool operator==(Rectangle a,Rectangle b)
{
return ((a.Height==b.Height)&&(a.Width==b.Width));
} // 重载操作符 !=
public static bool operator!=(Rectangle a,Rectangle b)
{
return !(a==b);
} // 重载操作符 >
public static bool operator>(Rectangle a,Rectangle b)
{
return a.Area>b.Area;
}
// 重载ToString
public override String ToString()
{
return "高=" + Height + ",宽=" + Width;
} public static void Main()
{
// 实例化矩形并设置各自属性
Rectangle objRect3 =new Rectangle(10,15);
Console.WriteLine("矩形#3 " + objRect3);
}
"矩形#3 " + objRect3第一个参数是字符串类型,后面一个是非字符串类型, 这里应用到了string 类型的 + 操作符重载。运行库自动将其转换为如下形式:
"矩形#3 " + objRect3.ToString()出于性能考虑,建议使用后面这个表达式,如此可省却一次转换判断和转换过程。
Console.WriteLine("矩形#3 " + objRect3);
相当于
Console.WriteLine("矩形#3 " + objRect3.ToString());
自动寻找添加的
__________________________________
get、set是属性过程,它是对类成员变量的一个保护接口。