c# - 无法在 .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 所述,扩展另一个类似乎也可以工作。
我错过了什么?
解决方案
我可以确认VS2019无法识别已导入签名的扩展方法。
您应该能够通过使用包含该类的命名空间来使用扩展方法。
using <yourextensionmethodnamespace>;
然后像这样称呼它
configuration.Get<WhateverType>("key");
推荐阅读
- java - 如何将 Spring REST Projections 与自定义控制器一起使用
- python - 内存地址 - 它对程序员有什么用?
- r - 使用 nlsLM 函数查找非线性模型的初始条件
- java - Grails 初始化类路径时出错:无法从 '10.0.2' 确定 java 版本
- visual-studio-code - 我无法在 VSCode 中为 D3D12 配置包含路径
- javascript - 如何在 getJSON 中使用 append
- azure - Azure 函数应用程序上的 routePrefix 被忽略
- python-3.x - 做数据透视表时出现NaN
- python - 使用 Python ssh 然后运行 bash 脚本。我需要在屏幕上显示的正在运行的 bash 脚本的输出
- php - 自己包中的路由问题-Laravel 5.6