Методи Класу
Як і структури, класи також можуть містити методи. Синтаксис створення та виклику методів також дуже схожий.
Наприклад, можна створити клас з назвою Rectangle
з атрибутами width
і height
та методом area
, який обчислює площу об'єкта прямокутника на основі значень width
і 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()}"); } }
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
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
Методи Класу
Свайпніть щоб показати меню
Як і структури, класи також можуть містити методи. Синтаксис створення та виклику методів також дуже схожий.
Наприклад, можна створити клас з назвою Rectangle
з атрибутами width
і height
та методом area
, який обчислює площу об'єкта прямокутника на основі значень width
і 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()}"); } }
Дякуємо за ваш відгук!