开发者

What is wrong with my implementation of: c# extension methods

开发者 https://www.devze.com 2022-12-10 02:34 出处:网络
the source is throwing the error: \'nn.asdf\' does not contain a definition for \'extension_testmethod\'

the source is throwing the error:

'nn.asdf' does not contain a definition for 'extension_testmethod'

and i really don't unterstand why...

using System.Linq;
using System.Text;
using System;

namespace nn
{
    pub开发者_运维知识库lic class asdf
    {
        public void testmethod()
        {
        }
    }
}
namespace nn_extension
{
    using nn;
    //Extension methods must be defined in a static class
    public static class asdf_extension
    {
        // This is the extension method.
        public static void extension_testmethod(this asdf str)
        {
        }
    }
}
namespace Extension_Methods_Simple
{
    //Import the extension method namespace.
    using nn;
    using nn_extension;
    class Program
    {
        static void Main(string[] args)
        {
            asdf.extension_testmethod();
        }
    }
}

any ideas?


An extension method is a static method that behaves like an instance method for the type being extended, that is, you can call it on an instance of an object of type asdf. You can't call it as if it were a static method of the extended type.

Change your Main to:

asdf a = new asdf();
a.extension_testmethod();

Of course, you can always call like a simple, static, non-extension method of the declaring type (asdf_extension):

asdf_extension.extension_testmethod(null);


Extension methods apply to class instances:

var instance = new asdf();
instance.extension_testmethod();
0

精彩评论

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