简体   繁体   English

如何在通用构造函数中获取类名

[英]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 ? 这显然行不通,但是有什么方法可以做到……或者我只需要在构造函数中实例化该类的新实例,然后执行_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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM