minhas informações de contato
Correspondência[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
1、Sobrecarga do operador
A sobrecarga do operador refere-se à redefinição dos operadores integrados do C#.
programador Tipos de operadores definidos pelo usuário também podem ser usados. Um operador sobrecarregado é uma função com um nome especial, definido pela palavra-chave operador seguida pelo símbolo do operador. Como outras funções, os operadores sobrecarregados possuem um tipo de retorno e uma lista de parâmetros.
2. Defina a sobrecarga do operador na classe Box
public class Box
{
private double length;
[Description("长度")]
public double Length
{
get { return length; }
set { length = value; }
}
private double width;
[Description("宽度")]
public double Width
{
get { return width; }
set { width = value; }
}
private double height;
[Description("高度")]
public double Height
{
get { return height; }
set { height = value; }
}
public double GetVolume()
{
return length * width * height;
}
public static bool operator == (Box box1, Box box2)
{
return (box1.length == box2.length) && (box1.width == box2.width) && (box1.height == box2.height);
}
public static bool operator != (Box box1, Box box2)
{
return (box1.length != box2.length) || (box1.width != box2.width) || (box1.height != box2.height);
}
}
3. Aplicar classe Box
Box box1 = new Box();
Box box2 = new Box();
Box box3 = new Box();
double volume = 0.0;
box1.Length = 3.0;
box1.Width = 4.0;
box1.Height = 5.0;
volume=box1.GetVolume();
Console.WriteLine($"Box1的体积是{volume}");
box2.Length = 6.0;
box2.Width = 7.0;
box2.Height = 8.0;
volume = box2.GetVolume();
Console.WriteLine($"Box2的体积是{volume}");
bool flag=box1 == box2;
Console.WriteLine($"Box1==Box2:{flag}");
flag = box1 != box2;
Console.WriteLine($"Box1!=Box2:{flag}");
4. Resultados da operação