Näide: Meetodite jagamine erinevatesse klassidesse ja failidesse
Faili 1: Program.cs
using System;
class Program
{
static void Main()
{
// Call a method from another class
Helper.PrintWelcomeMessage();
// Call a method that returns a value
int sum = MathOperations.Add(5, 7);
Console.WriteLine($"Sum: {sum}");
// Call a method from an instance of a class
Greeter greeter = new Greeter("Alice");
greeter.SayHello();
}
}
Faili 2: Helper.cs
using System;
public static class Helper
{
// Static method (can be called without creating an object)
public static void PrintWelcomeMessage()
{
Console.WriteLine("Welcome to the multi-file C# example!");
}
}
Faili 3: MathOperations.cs
MathOperations.cs
public static class MathOperations
{
public static int Add(int a, int b)
{
return a + b;
}
public static int Multiply(int a, int b)
{
return a * b;
}
}
Faili 4: Greeter.cs
using System;
public class Greeter
{
private string _name;
// Constructor
public Greeter(string name)
{
_name = name;
}
// Instance method (requires an object to call)
public void SayHello()
{
Console.WriteLine($"Hello, {_name}!");
}
}
Kuidas see toimib?
1. Eraldi Failid
Selguse huvides on iga klass omaette .cs-failis.
Kõik failid kuuluvad samasse nimeruumi (kui pole täpsustatud, siis vaikimisi) ja projekti.
2. Staatilised Meetodid
Kuuluvad klassi enda alla, objekti pole vaja.
Näide: Helper.PrintWelcomeMessage().
3. Instantsimeetodid
Nõuab objekti loomist new funktsiooniga.
Näide:
Greeter g = new Greeter("Bob"); g.SayHello();
4. Kompilatsioon
Visual Studios või dotneti käsurealiideses kompileeritakse kõik projekti .cs-failid automaatselt kokku.