Métodos de Clase
Al igual que las estructuras, las clases también pueden tener métodos. La sintaxis para crear y llamar métodos también es muy similar.
Por ejemplo, se puede crear una clase llamada Rectangle
con los atributos width
y height
, y un método llamado area
, que calcula el área del objeto rectángulo en función de los valores de width
y height
:
index.cs
1234567class className { // ... other class code public returnType methodName(datatype param1, datatype param2, ...) { // code } }
index.cs
123456789101112131415161718192021222324252627using System; public class ConsoleApp { class Rectangle { public double width; public double height; public double area() { return width * height; } } public static void Main(string[] args) { Rectangle r1 = new Rectangle(); r1.width = 10; r1.height = 20; Rectangle r2 = new Rectangle(); r2.width = 14.7; r2.height= 17.9; Console.WriteLine($"Area of R1 is {r1.area()}"); Console.WriteLine($"Area of R2 is {r2.area()}"); } }
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Awesome!
Completion rate improved to 2.04
Métodos de Clase
Desliza para mostrar el menú
Al igual que las estructuras, las clases también pueden tener métodos. La sintaxis para crear y llamar métodos también es muy similar.
Por ejemplo, se puede crear una clase llamada Rectangle
con los atributos width
y height
, y un método llamado area
, que calcula el área del objeto rectángulo en función de los valores de width
y height
:
index.cs
1234567class className { // ... other class code public returnType methodName(datatype param1, datatype param2, ...) { // code } }
index.cs
123456789101112131415161718192021222324252627using System; public class ConsoleApp { class Rectangle { public double width; public double height; public double area() { return width * height; } } public static void Main(string[] args) { Rectangle r1 = new Rectangle(); r1.width = 10; r1.height = 20; Rectangle r2 = new Rectangle(); r2.width = 14.7; r2.height= 17.9; Console.WriteLine($"Area of R1 is {r1.area()}"); Console.WriteLine($"Area of R2 is {r2.area()}"); } }
¡Gracias por tus comentarios!