我有以下两个扩展方法(方法的主体对我的问题来说不是特别重要,但无论如何包括代码)
public static class DictionaryExtensions
{
public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key, TValue defaultValue)
{
return (source.ContainsKey(key) ? source[key] : defaultValue);
}
}
public static class WebExtensions
{
public static T GetValue<T>(this HttpContext context, string name, T defaultValue)
{
object value = context.Request.Form[name] ?? context.Request.QueryString[name];
if (value == null) return defaultValue;
return (T)value;
}
}
这两个方法共享相同的名称,但它们扩展了两种截然不同的类型。我希望下面的代码很简单,并且编译器能够选择适当的扩展方法:
var myDict = new Dictionary<int, string>()
{
{ 1, "foo" },
{ 2, "bar" }
};
var result = myDict.GetValue(5, "baz");
但是,由于某些未知原因,Visual Studio 拒绝编译我的代码并出现以下编译时错误:“类型‘System.Web.HttpContext’在未引用的程序集中定义。您必须添加引用组装'System.Web'”。这个错误告诉我编译器选择了 WebExtensions 类中的 GetValue 扩展方法,而不是 DictionaryExtension 类中的方法。
我能够通过以下方式解决问题:
var result = DictionaryExtensions.GetValue(myDict, 5, "baz");
但我试图理解为什么编译器一开始就感到困惑。有人知道为什么吗?
最佳答案
另一种选择是将您的 2 个扩展类分解为单独的命名空间,并且不要在 WebExtensions
类所在的位置添加 using
语句你的消费代码。这样编译器就不会尝试将 GetValue
解析为 WebExtensions
。
关于c# - 两个同名的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27724720/