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

.NET泛型扩展方法中无法访问实现类静态属性的问题

配置注入的泛型扩展方法问题

我在.NET中注入配置选项时,最初采用以下实现方式:

IHost host = Host.CreateDefaultBuilder(args)
  .ConfigureServices((host, services) =>
  {
    IConfiguration config = host.Configuration;
    ...
    services.Configure<SomeConfig>(
      config.GetSection(new SomeConfig().SectionKey));
  }).Build();

对应的接口与实现类:

public interface IConfig
{
  public string SectionKey { get; }
}

public class SomeConfig : IConfig
{
  public string SectionKey => "SomeConfig";
  ...
}

由于SectionKey在类的所有实例中值都相同,我尝试将其改为静态属性:

IHost host = Host.CreateDefaultBuilder(args)
  .ConfigureServices((host, services) =>
  {
    IConfiguration config = host.Configuration;
    ...
    services.Configure<SomeConfig>(
      config.GetSection(SomeConfig.SectionKey));
  }).Build();

public interface IConfig
{
  public static string SectionKey { get; }
}

public class SomeConfig : IConfig
{
  public static string SectionKey => "SomeConfig";
  ...
}

为了简化配置注入,我想创建泛型扩展方法,期望调用方式如下:

IHost host = Host.CreateDefaultBuilder(args)
  .ConfigureServices((host, services) =>
  {
    IConfiguration config = host.Configuration;
    ...
    services.Config<SomeConfig>(config);
  }).Build();

但目前创建的扩展方法只能通过实例化T来获取非静态的SectionKey:

public static class ConfigurationExtensions
{
  public static IServiceCollection Config<T>(
    this IServiceCollection self, IConfiguration config)
    where T : class, IConfig, new()
  {
    string key = new T().SectionKey;
    IServiceCollection output = self.Configure<T>(
      config.GetSection(key));

    return output;
  }
}

我尝试在接口中定义静态属性和常量,让实现类去实现:

public interface IConfig
{
  public string SectionKey { get; }
  public static string SectionKeyStatic { get; } = default!;
  public const string SectionKeyConst = default!;
}

public class SomeConfig : IConfig
{
  public string SectionKey => "SomeConfig";
  public static string SectionKeyStatic => "SomeConfig";
  public const string SectionKeyConst = "SomeConfig";
}

但在扩展方法中,只能访问接口的静态成员,无法通过泛型T访问实现类的静态属性和常量:

public static class ConfigurationExtensions
{
  public static IServiceCollection Config<T>(
    this IServiceCollection self, IConfiguration config)
    where T : class, IConfig, new()
  {
    string thisWorks = IConfig.SectionKeyStatic;
    string thisToo = IConfig.SectionKeyConst;
    string thisFails = T.SectionKeyStatic; // 编译错误
    string thisAlso = T.SectionKeyConst; // 编译错误
    ...
  }
}

我搞不懂为什么会这样,也不知道怎么解决,现在只能继续用实例化的方式,希望找到更好的解决方案。

内容的提问来源于stack exchange,提问作者Konrad Viltersten

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:23:15