带有自定义类的扩展方法

本文关键字:扩展 方法 自定义 | 更新日期: 2023-09-27 18:18:55

我试图扩展我的自定义类,并遇到一个问题,它无法找到扩展方法。我有并且可以扩展任何内置的类,甚至包含在DLL中的类。我不知道这是一个编译错误还是我做错了什么。胡乱拼凑的一个小程序为例,不会编译…

扩展名:

namespace ExtensionMethodTesting.Extension
{
    public static class Extension
    {
        public static void DoSomething(this ExtensionMethodTesting.Blah.CustomClass r)
        {
        }
    }
}

下面是自定义类:

namespace ExtensionMethodTesting.Blah
{
    public class CustomClass
    {
        public static void DoNothing()
        {
        }
    }
}

调用它的代码如下:

using ExtensionMethodTesting.Blah;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExtensionMethodTesting.Extension;
namespace ExtensionMethodTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomClass.DoNothing();
            CustomClass.DoSomething();
        }
    }
}

我一定是错过了什么…无论如何,确切的错误只是为了澄清:

错误1 'ExtensionMethodTesting.Blah。CustomClass'不包含'DoSomething'的定义c:'users'damon'documents'visual studio 2013'Projects'ExtensionMethodTesting'ExtensionMethodTesting'Program.cs 16 25 ExtensionMethodTesting

带有自定义类的扩展方法

扩展方法需要一个对象的实例。要使用它,你必须把new加到CustomClass上。

var custom = new CustomClass();
custom.DoSomething();

您需要实例化CustomClass的对象来使用它的扩展方法。

CustomClass obj = new CustomClass();
obj.DoSomething();