mercredi 6 juin 2018

How to get class name in generic constructor

Is there a way to get the class name in the contstructor so it can be used for multiple methods later on?

This doesn't work obviously, but is there some way to do this...or do I just need to instantiate a new instance of that class in the constructor, then do _className = classInstance.GetType().Name?

public class Repository<TEntity> : IRepository<TEntity>
    where TEntity : class, Domain.IEntity, new()
{
    private APIContext _apiContext;
    private string _className;

    public Repository(APIContext apiContext)
    {
        _apiContext = apiContext;
        _className = TEntity.GetType().Name; <---- any way to do this?
    }

    public async Task<TEntity> GetByIdAsync(int id)
    {

        string strPath = string.Format("/{0}s/v1/{1}", _className, id); <----**used here**

        string jsonStringResponse = await RestAPIHelper.Get(_apiContext, strPath);
        TEntity entity = JsonConvert.DeserializeObject<TEntity>(jsonStringResponse);
        return entity;
    }
}





Aucun commentaire:

Enregistrer un commentaire