![]()
Generic yapı farklı veri türleriyle kullanılabilen Interface , class , method veya herhangi bir yöntem oluşturmamıza olanak tanır. Bu, kodumuzu herhangi bir tipe bağımlı olmazksızın esnek bir biçimde kullanmamızı sağlar. Şimdi C#’ta generik sınıf ve metot oluşturma olayına bakalım.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
static void Generic<T>(ref T a, ref T b) { T temp = a; a = b; b = temp; } int x = 1, y = 2; Generic(ref x, ref y); Console.WriteLine($“x = {x}, y = {y}”); // Outputs: x = 2, y = 1 string str1 = “Hello”, str2 = “World”; Generic(ref str1, ref str2); Console.WriteLine($“str1 = {str1}, str2 = {str2}”); // Outputs: str1 = World, str2 = Hello decimal dec1 = 12.7m , dec2 = 20; Generic(ref dec1, ref dec2); Console.WriteLine($“dec1 = {dec1}, dec2 = {dec2}”); // Outputs: dec1 = 20, dec2 = 12.7 bool bol1 = true, bol2 = false; Generic(ref bol1, ref bol2); Console.WriteLine($“bol1 = {bol1}, bol2 = {bol2}”); // Outputs: bol1 = false, bol2 = true |
Şimdide bi class ve interface üzerinden örnek yapalım.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
public interface IComparable<T> { public int CompareTo(T other); } public class Person : IComparable<Person> { public string Name { get; set; } public int Age { get; set; } public int CompareTo(Person person) { return this.Age.CompareTo(person.Age); } } class Program { static void Main(string[] args) { Person per1 = new Person { Name = “Ali”, Age = 30 }; Person per2 = new Person { Name = “Bahar”, Age = 40 }; var result = per1.CompareTo(per2); Console.WriteLine(result > 1 ? true : false); //Output: False } } |
Başka örnek
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public class Utils { public static T Max<T>(List<T> items) where T : IComparable<T> { if (items.Count == 0) { throw new ArgumentException(“Liste boş olamaz.”); } T max = items[0]; foreach (var item in items) { if (item.CompareTo(max) > 0) { max = item; } } return max; } } class Program { static void Main(string[] args) { List<int> numbers = new List<int> { 1, 5, 3, 9, 2, 17 }; Console.WriteLine(Utils.Max(numbers)); // Outputs: 17 List<string> strings = new List<string> { “Elma”, “Armut”, “Kayısı”, “Şeftali”}; Console.WriteLine(Utils.Max(strings)); // Outputs: Şeftali List<decimal> decimals = new List<decimal> { 2.7m, 12.7m, 20, 20.1m }; Console.WriteLine(Utils.Max(decimals)); // Outputs: 20.1 } } |
sağlıcakla kalın…








Bir yanıt yazın