Sayfalar

28 Ağustos 2019 Çarşamba

Generics Sınıf ve Metotlar


Birden fazla sınıfta kullanılacak aynı metotlar mevcut ise bunu Generic metot ve sınıflar ile halledebiliriz. Örneğin Product ve Customer adlı iki sınıfımız mevcut olsun ve her ikisinde de belli mettotlar kullanılsın. Bu bağlamda bir Genereic interface oluşturup kullanım alanlarına göre tipleri atayabiliriz.

Örn:
Bir IRepository interface'i oluşturuyoruz ve içine ortak kullanılacak metotları koyuyoruz.
<T> (Type) ile ortak bir nesne belirtiyoruz.

public interface IRepository<T> 
{
    void Add(T entity);
    void Update(T entity);
    void Delete(T entity);
    List<T> GetAll();
    List<T> SearchByName(string key);
    List<T> GetByUnitPriceAToZ();
    List<T> GetByUnitPriceZToA();
}

Sonrasında IProductDal IRepository uyguluyoruz ve Tipini sen "Product" olacaksın diye belirtiyoruz.

public interface IProductDal :IRepository<Product>
{
 
}

Artık ProductDal sınıfında ki işlemlerde product nesnesini kullanabiliriz.

public class ProductDal : IProductDal
{
    public void Add(Product product)
    {
        using (ETradeContext context = new ETradeContext())
        {
            context.Products.Add(product);
            context.SaveChanges();
        }
    }
 
    public void Delete(Product product)
    {
        using (ETradeContext context = new ETradeContext())
        {
            var productInDb = context.Entry(product);
            productInDb.State = EntityState.Deleted;
            context.SaveChanges();
        }
    }
----
Daha sonra Customer sınıfına aynı işlemlri yaparak Genericleri kullanmış oluyoruz.

public interface ICustomerDalIRepository<Customer>
{
 
}



public class CustomerDalICustomerDal
{
    public void Add(Customer entity)
    {
        throw new NotImplementedException();
    }
 
    public void Delete(Customer entity)
    {
        throw new NotImplementedException();
    }






---








---

MVC LOADING TOO SLOW ISSUE