泛型方法隐藏非泛型方法,如何显式调用目标非泛型方法?
问题分析与解决方案
你遇到的是C#重载解析的优先级问题:泛型版本的GetByIdAsync<TId>被编译器优先匹配,而非你期望的int参数的非泛型版本。以下是具体原因和解决办法:
核心原因
当调用GetByIdAsync(serviceRequestId)时,若serviceRequestId的类型不是精确的int(比如long),编译器会认为泛型方法的匹配度更高(无需隐式类型转换);即使参数是int,接口继承关系也可能导致编译器误选泛型重载。
解决办法
1. 强制参数类型匹配
如果serviceRequestId不是int类型,显式转换为int,让编译器优先匹配非泛型方法:
ServiceRequest sr = await _sReqRepo.GetByIdAsync((int)serviceRequestId);
2. 显式接口方法调用
将实例强制转换为IRepository<ServiceRequest>接口后调用方法,明确指定目标重载:
IRepository<ServiceRequest> repo = (IRepository<ServiceRequest>)_sReqRepo; ServiceRequest sr = await repo.GetByIdAsync(serviceRequestId);
3. 调整方法签名(若允许修改代码)
通过添加可选参数或重命名方法,彻底避免重载冲突:
// 添加可选CancellationToken参数,与泛型方法签名区分 public async Task<ServiceRequest> GetByIdAsync(int id, CancellationToken cancellationToken = default) { return await _context.ServiceRequests .Include(sReq => sReq.ServiceResponse) .SingleOrDefaultAsync(c => c.ServiceRequestId == id, cancellationToken); } // 或直接重命名非泛型方法 public async Task<ServiceRequest> GetByIdIntAsync(int id) { return await _context.ServiceRequests .Include(sReq => sReq.ServiceResponse) .SingleOrDefaultAsync(c => c.ServiceRequestId == id); }
内容的提问来源于stack exchange,提问作者omike
相关产品推荐
相关产品推荐

