有没有办法在构造函数中获取类名,以便以后可以将其用于多个方法?
这显然不起作用,但是有什么方法可以做到这一点...或者我只需要在构造函数中实例化该类的新实例,然后执行 _className = classInstance.GetType() .名称
?
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;
关于c# - 如何在通用构造函数中获取类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50720932/