C# ile kod güvenliğini sağlamanın en önemli yollarından birisi kuşkusuz ki Generic’ler olmakta. Hem performansı hemde kodun doğru kullanımını sağlanabilir. Örneklere geçelim:
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 38 39 40 41 42 43 |
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { SummerSchoolList<Student> collection = new SummerSchoolList<Student>(); //collection.Add<bool>(5, true); } } public class SummerSchoolList<T> where T: Student, new() { ArrayList list = new ArrayList(); public void Add<U>(T item, U item2) { list.Add(item); } void Remove(T item) { } } public class Student { public string Name { get; set; } public string Surname { get; set; } public Student() { } } } |
public class SummerSchoolList<T> where T: Student, new() kısmında generic bir T belirliyoruz ve where T: Student ile T’nin Student ve Student Class’ından türeyecek olan sınıflara izin verilmesini sağladık. new() ile class’ın boş parametre alan constructor’unun etkin kılınması sağlanmıştır.
İyi Çalışmalar 🙂