有没有办法在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;
}
}
答案 0 :(得分:4)
应该是
_className = typeof(TEntity).Name;