【问题标题】:Extension Method to an item of a ReadOnlyCollectionReadOnlyCollection 项目的扩展方法
【发布时间】:2014-09-19 19:38:23
【问题描述】:

我有一个自定义接口类型 (IMyInterface) 的 ReadOnlyCollection。我想向自定义接口类型添加扩展方法。但是,当我访问 ReadOnlyCollection 中的项目时,我的扩展方法没有显示。 这是我的代码:

public static class MyClass
{
    public static string GetValueByName(this IMyInterface myInterface, string myName)
    {
        foreach (var name in myInterface.names) //
        {
            if (myName == name)
                return name;
        }
        throw new ArgumentException(myName + " not found.");
    }
}

当我尝试通过执行类似的操作来访问它时,

MyMethod[0].<extension method>   //MyMethod returns a ReadOnlyCollection<IMyInterface>

扩展方法未显示在 MyMethod[0](在 Visual Studio 中)之后的可用弹出窗口中,这意味着它不可用。我可能会错过什么?是否可以为 ReadOnlyCollection 中的项目添加扩展方法?

【问题讨论】:

  • 听起来你没有为扩展的命名空间包含using
  • 哇!我认为 Visual Studio 会自动检测到并提示我添加它。没有意识到它缺少命名空间!谢谢@NeilSmith。成功了!
  • 我想知道为什么人们为自己的类/接口使用扩展方法!
  • @Yogee 你还怎么提供接口方法的具体实现?
  • @eranotzap 这就是您在接口上创建扩展方法时所做的事情。为您可以控制其来源的类创建扩展方法也是有意义的,但与接口相比,这是一种更狭窄/不寻常的情况。

标签: c# extension-methods readonly-collection


【解决方案1】:

猜猜我会把它变成答案:

您没有为扩展的命名空间包含 using 语句。

例如,如果您在 MyNamespace 中编写了扩展,则必须在使用该扩展的类中包含 using MyNamespace

【讨论】:

    猜你喜欢
    • 2011-07-28
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多