【问题标题】:Extension method marked as ambiguous扩展方法标记为不明确
【发布时间】:2016-02-04 06:11:04
【问题描述】:

我在使用扩展方法时遇到问题。另一种方法导致了同样的错误,现在我又遇到了同样的问题。编译时 - Visual Studio 将我的扩展方法标记为模棱两可。但我很确定这是我唯一的实现 -

我的扩展方法是——

public static class TypeInfoExtensions
{
    /// <summary>
    /// Gets the property dictionary.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="types">The types.</param>
    /// <returns></returns>
    public static IEnumerable<Dictionary<string, object>> GetPropertyDictionaryList<T>(this IEnumerable<TypeInfo> types) where T : Attribute
    {
        return types.Select(x => x.GetPropertyDictionary<T>());
    }
    /// <summary>
    /// Gets the property dictionary.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="type">The type.</param>
    /// <returns></returns>
    public static Dictionary<string, object> GetPropertyDictionary<T>(this TypeInfo type) where T : Attribute
    {
        var dict = new Dictionary<string, object>();

        return dict;
    }
}

而且是这样使用的——

var model = ...... // other codes

var parameters = Assembly.GetAssembly(typeof (Model.Domain.Tenants.Tenant)).DefinedTypes;
model.AvailableProperties = parameters.GetPropertyDictionaryList<MessageTemplateItem>().ToList()

这是我唯一的实现,我刚刚添加了它,但是 VS 显示这个错误 -

错误 81 以下方法之间的调用不明确或 特性: 'SMP.Core.Extensions.TypeInfoExtensions.GetPropertyDictionary(System.Reflection.TypeInfo)' 和 'SMP.Core.Extensions.TypeInfoExtensions.GetPropertyDictionary(System.Reflection.TypeInfo)'

我认为这可能是一个临时错误,可能是清理解决方案而不是清理引用或缓存。但如果有其他人遇到此错误,我将非常感谢您的反馈。

更新奇怪的是,这段代码有效 -

public static IEnumerable<Dictionary<string, object>> GetPropertyDictionaryList<T>(this IEnumerable<TypeInfo> types) where T : Attribute
{
    return types.Select(x => GetPropertyDictionary<T>(x));
}

我现在真的很困惑,到目前为止我知道这些对于扩展方法是相同的 -

GetPropertyDictionary<T>(x)
x.GetPropertyDictionary<T>()

各位有什么想法吗?

【问题讨论】:

  • 重启VS看看是否消失
  • 我在使用动态类型的扩展方法时遇到了问题。不要使用“var parameters =”,而是使用实际类型,看看是否可以为您解决问题。
  • 我编译了你的代码,它工作正常。尝试从 bin 和 obj 文件夹中删除所有 dll,看看是否有效。
  • @ELewis 我认为这不是问题。它调用成功,这是该方法内的第二次调用,导致问题。
  • 你能提供一个minimal reproducible example吗?这样可以更轻松地为您提供帮助。

标签: c# .net


【解决方案1】:

我遇到了同样的问题。我在项目 A 中声明了一个扩展方法。在这个项目中使用它时,它在另一个项目 B 中不起作用。在那里它被标记为不明确。但是,在项目 B 中以静态方式调用它是可行的。

在整个解决方案或参考中按字符串搜索时,我找不到项目 A 中的任何其他实现。

问题终于出现了:我不小心把A项目的扩展方法的源文件的链接添加到了B项目,把B项目的源文件的链接去掉就解决了。

【讨论】:

  • 请评论否决票,如果有问题或无法理解,我想改进答案,但这只有在我获得更多信息时才有可能。
【解决方案2】:

我刚刚遇到了同样的问题。如果不是源代码控制,我永远不会追查到它。

该项目多年来一直很好地使用扩展方法。然后,经过一些更改所有扩展方法的使用开始出现:

以下方法或属性之间的调用不明确:...

调用的两个项目具有完全相同的命名空间和签名。

csproj 文件的差异揭示了问题所在。 obj 目录的输出可执行文件不知何故被添加为提示路径中的引用。

类似:

<ItemGroup>
    <Reference Include="OutputExecutable">
        <HintPath>obj\DEBUG\OutputExecutable.exe</HintPath>
    </Reference>
</ItemGroup>

删除那个错误的条目让一切都重新建立起来。它最初是如何到达那里的,目前仍是一个谜。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-15
    • 2013-06-21
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多