You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#泛型接口中nameof返回泛型占位符而非实际类型名问题

问题原因

nameof 是C#的编译时语法糖,仅会提取代码中符号的字面名称,在编译 TraceManager<TManager> 泛型类的阶段,nameof(TManager) 就已经被替换为固定字符串 "TManager",和后续实例化时传入的具体泛型参数没有关联,因此无法得到你预期的实际类型名称。

解决方案

如果需要获取运行时实际传入的泛型参数类型名称,改用 typeof 运算符读取泛型参数的类型元数据即可:

public sealed class TraceManager<TManager> : ITraceManager<TManager> where TManager : class
{
    // 替换nameof为typeof(TManager).Name
    public string Name => $"Foo Bar - {typeof(TManager).Name}";        

    public void DisplayName()
    {
        Console.WriteLine($"{Name}");            
    }
}

如果需要带命名空间的完整类型名,将 .Name 替换为 .FullName 即可。


内容的提问来源于stack exchange,提问作者Ali Khakpouri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:45:03