无法向 .NET Core 中的 IConfiguration 添加扩展方法(但正在处理其他 类)
Can't add extension method to IConfiguration in .NET Core (but working on other classes)
我已将以下扩展方法添加到我的项目中。
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;
}
}
出于某种原因,它似乎无法在智能感知中通过,并且编译器唠叨说字符串不能作为第二个参数传递。谷歌搜索验证了扩展方法确实适用于接口,唯一的要求是签名不同,因为它们不能覆盖。
You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.
在我看来,它们确实不同,因为原始版本的传入参数与我的字符串版本不同。
public static T Get<T>(this IConfiguration self, string x) { ... }
public static T Get<T>(this IConfiguration self, Action<BinderOptions> x) { ... }
扩展另一个 class 似乎也有效 as described at MSDN。
我错过了什么?
我可以确认VS2019无法识别已经导入的带有签名的扩展方法
您应该能够通过使用包含 class.
的命名空间来使用扩展方法
using <yourextensionmethodnamespace>;
然后这样调用
configuration.Get<WhateverType>("key");
我已将以下扩展方法添加到我的项目中。
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;
}
}
出于某种原因,它似乎无法在智能感知中通过,并且编译器唠叨说字符串不能作为第二个参数传递。谷歌搜索验证了扩展方法确实适用于接口,唯一的要求是签名不同,因为它们不能覆盖。
You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.
在我看来,它们确实不同,因为原始版本的传入参数与我的字符串版本不同。
public static T Get<T>(this IConfiguration self, string x) { ... }
public static T Get<T>(this IConfiguration self, Action<BinderOptions> x) { ... }
扩展另一个 class 似乎也有效 as described at MSDN。
我错过了什么?
我可以确认VS2019无法识别已经导入的带有签名的扩展方法
您应该能够通过使用包含 class.
的命名空间来使用扩展方法using <yourextensionmethodnamespace>;
然后这样调用
configuration.Get<WhateverType>("key");