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



有没有办法在结构器中获取类名,以便以后可以将其用于多种方法?

这显然不起作用,但是有没有办法做到这一点...还是我只需要在构造函数中实例化该类的新实例,然后_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;
}
}

它应该是

_className = typeof(TEntity).Name; 

一种比公认的答案更简单的方法:

_className = nameof(TEntity)

最新更新