代码之家  ›  专栏  ›  技术社区  ›  crichavin

如何在泛型构造函数中获取类名

  •  2
  • crichavin  · 技术社区  · 8 年前

    是否有方法在contstructor中获取类名,以便以后可以将其用于多个方法?

    这显然不起作用,但是有什么方法可以做到…或者我只需要在构造函数中实例化该类的一个新实例,然后 _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;
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   Dmitry Pavliv    8 年前

    应该是

    _className = typeof(TEntity).Name;