C# generic tiplerde constraint kullanımı
Genericler .net 2.0 ile hayatımıza girdi. Şu aralar web projelerimde kullanmak için kendi altyapımı oluşturuyorum ve generic bir base class yapmam gerekiyor. Design patternlari inceledigim de hep complex code tipleri ile karşılaştım( zaten anlaması zor konular )
class Base { }
class Test
where U : struct
where T : Base, new() { }
Genericler bildigimiz gibi T türünden tanımlarsınız ve siz ne verirseniz onun türünden olurlar Yukarıdaki kod ilk bakışta complex geliyor alışık olmadığımız generic class yapıları var. Generic classlarda where kullanabiliyoruz peki bize ne faydası var bunun eğer classlarının oluşturulurken yani constructior lar çağırılırken diyelim ki bu T türü bir struct olmalı veya disposable, iquaryable olmalı gibi kısıtlamalar eklemek istenilebilir. Msdn de buldugum çeşitli constraintleri tablosu
| Constraint | Description |
|---|---|
| where T: struct | The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information. |
| where T : class | The type argument must be a reference type, including any class, interface, delegate, or array type. (See note below.) |
| where T : new() | The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last. |
| where T : <base class name> | The type argument must be or derive from the specified base class. |
| where T : <interface name> | The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic. |
| where T : U | The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint. |
Bir örnek yapalım;
using System;
using System.Data;
using System.Runtime.Serialization;
class Listem where T : ISerializable
{
}
class MyStruct where T : struct
{
}
class Sinif where V : class, new()
{
}
class Test
{
}
class Program
{
static void Main()
{
// T türüne karşılık gelen ISerializable türünden implemente edilmiş olmak zorunda
Listem _listem = new Listem();
Listem() llll=new Listem();
// Int türü struct türünde ve düzgün compile edecek
MyStruct python = new MyStruct();
//Parametresiz bir class olmalı
Sinif test = new Sinif();
}
}
Yukarıdaki kodda Listem generic sınıfı serialize edibilir olmalı diyorum eğer class a bu constrainti vermeseydik <int>verdigimizde de çalışacaktı fakat <int> Ienumarable bir tür ISerializable olmadıgı için aşağıdaki hatayı verdi.
2. Örnek te ise new oluşturlacak bu generic class bir struct olmalı diyorum
3. class ta ise yapılmak istenen aslında default constructior ile alakalı bir durum bildigimiz gibi biz yazmasakta .net default constructiori oluşturuyor. where V : class, new() diyerek T türü parametre almayacak bir class olmalı diyoruz.
