c# - 两个同名的扩展方法

标签 c# extension-methods

我有以下两个扩展方法(方法的主体对我的问题来说不是特别重要,但无论如何包括代码)

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/

相关文章:

c# - 扩展接口(interface)模式

c# - 对 XDocument 中的所有元素进行排序

C#访问另一个用户的注册表

extension-methods - 使用毫秒 : xpath functions inside XPathExpression

c# - 有没有办法使 .NET Cast<T> 扩展方法使用用户定义的隐式转换运算符?

c# - 通用列表的扩展方法

c# - 修改 string.Substring

c# - 使命名元组的名称出现在序列化的 JSON 响应中

c# - 如何克服 C# 中缺乏友元的问题?

c# - 在 C# 中自动换行字符串溢出并给出已自动换行的行数