首页 > 解决方案 > 无法在 .NET Core 中向 IConfiguration 添加扩展方法(但在其他类上工作)

问题描述

我在我的项目中添加了以下扩展方法。

public static class Extensions
{
  public static T Get<T>(this IConfiguration self, string path)
  {
    IConfigurationSection section = self.GetSection(path);
    T output = section.Get<T>();

    return output;
  }
}

出于某种原因,它似乎无法通过智能感知实现,并且编译器会抱怨不能将字符串作为第二个参数传递。谷歌搜索验证扩展方法确实适用于接口,唯一的要求是签名不同,因为它们不能覆盖。

您可以使用扩展方法来扩展类或接口,但不能覆盖它们。永远不会调用与接口或类方法具有相同名称和签名的扩展方法。

在我看来,它们确实不同,因为原始版本的传入参数与我的字符串版本不同。

public static T Get<T>(this IConfiguration self, string x) { ... }
public static T Get<T>(this IConfiguration self, Action<BinderOptions> x) { ... }

如 MSDN 所述,扩展另一个类似乎也可以工作。

我错过了什么?

标签: c#.net-coreextension-methods

解决方案


我可以确认VS2019无法识别已导入签名的扩展方法。

您应该能够通过使用包含该类的命名空间来使用扩展方法。

using <yourextensionmethodnamespace>;

然后像这样称呼它

configuration.Get<WhateverType>("key");

推荐阅读