开发者

C# extension method doesn't seem to exist

I can't seem to get the following extension method to be found in another class in the same namespace开发者_运维问答 (MyProject.Util).

using System.Collections.Specialized;

namespace MyProject.Util
{
    public static class Extensions
    {
        public static string Get(
             this NameValueCollection me,
             string key,
             string def
        )
        {
            return me[key] ?? def;
        }
    }
}

As you can see it's basically another version of foo[bar] ?? baz, but I still don't understand why VS2008 fails to compile telling me that no version of Get takes two arguments.

Any ideas?


Are you importing your namespace (with using MyProject.Util) in the file where you're using the method? The error message might not be obvious because your extension method has the same name as an existing method.


You can't use the extension method like a static method as in NameValueCollection.Get. Try:

var nameValueCollection = new NameValueCollection();
nameValueCollection.Get( ...


Is the class in the same assembly as the class where it is being used? If no, have you added a reference to that assembly?


The following seems to work for me ...

using System.Collections.Specialized;

namespace MyProject.Util
{
    class Program
    {
        static void Main(string[] args)
        {
            var nvc = new NameValueCollection();
            nvc.Get(  )
        }
    }
}


namespace MyProject.Util
{
    public static class Extensions
    {
        public static string Get(
             this NameValueCollection me,
             string key,
             string def
        )
        {
            return me[key] ?? def;
        }
    }
}

Have you checked your target framework?


Works fine when I try it. There's really only one failure mode: forgetting to add a using statement for the namespace that contains the extension method:

using System.Collections.Specialized;
using MyProject.Util;     // <== Don't forget this!
...
    var coll = new NameValueCollection();
    coll.Add("blah", "something");
    string value = coll.Get("blah", "default");


I had a similar issue recently and traced it down to not referencing System.Core (the project was compiled against 3.5, but that reference had accidentally been removed while experimenting with VS2010/.Net 4.0).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜