我的实现有什么问题:c#扩展方法

Dav*_*vid 1 .net c# extension-methods

源是抛出错误:

'nn.asdf' does not contain a definition for 'extension_testmethod'
Run Code Online (Sandbox Code Playgroud)

我真的不知道为什么......

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

namespace nn
{
    public 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Meh*_*ari 6

扩展方法是一种静态方法,其行为类似于被扩展类型的实例方法,也就是说,您可以在类型对象的实例上调用它asdf.您不能将其称为扩展类型的静态方法.

将您更改Main为:

asdf a = new asdf();
a.extension_testmethod();
Run Code Online (Sandbox Code Playgroud)

当然,您总是可以像声明类型()的简单static,非扩展方法一样调用:asdf_extension

asdf_extension.extension_testmethod(null);
Run Code Online (Sandbox Code Playgroud)