Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Metodi di Classe | Introduzione alla Programmazione Orientata agli Oggetti (OOP)
C# Oltre le Basi

bookMetodi di Classe

Proprio come le struct, anche le classi possono avere metodi. La sintassi per creare e richiamare metodi è anch'essa molto simile.

Ad esempio, è possibile creare una classe chiamata Rectangle con attributi width e height e un metodo chiamato area, che calcola l'area dell'oggetto rettangolo in base ai valori di width e height:

index.cs

index.cs

copy
1234567
class className { // ... other class code public returnType methodName(datatype param1, datatype param2, ...) { // code } }
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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()}"); } }
question mark

Quale delle seguenti è un metodo valido?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 7

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Awesome!

Completion rate improved to 2.04

bookMetodi di Classe

Scorri per mostrare il menu

Proprio come le struct, anche le classi possono avere metodi. La sintassi per creare e richiamare metodi è anch'essa molto simile.

Ad esempio, è possibile creare una classe chiamata Rectangle con attributi width e height e un metodo chiamato area, che calcola l'area dell'oggetto rettangolo in base ai valori di width e height:

index.cs

index.cs

copy
1234567
class className { // ... other class code public returnType methodName(datatype param1, datatype param2, ...) { // code } }
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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()}"); } }
question mark

Quale delle seguenti è un metodo valido?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 7
some-alt