Métodos de Classe
Assim como structs, classes também podem ter métodos. A sintaxe para criar e chamar métodos também é muito semelhante.
Por exemplo, é possível criar uma classe chamada Rectangle com os atributos width e height e um método chamado area, que calcula a área do objeto retângulo com base nos valores de width e 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()}"); } }
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Can you show me how to define a method inside a class?
How do I call a method from an instance of a class?
What is the difference between a method and a regular function in a class?
Awesome!
Completion rate improved to 2.04
Métodos de Classe
Deslize para mostrar o menu
Assim como structs, classes também podem ter métodos. A sintaxe para criar e chamar métodos também é muito semelhante.
Por exemplo, é possível criar uma classe chamada Rectangle com os atributos width e height e um método chamado area, que calcula a área do objeto retângulo com base nos valores de width e 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()}"); } }
Obrigado pelo seu feedback!