找不到扩展方法

Extension method not found

我有一个控制台应用程序模块,在单独的 Extensions 命名空间和 class 中有一个扩展方法,在 DataProcessor class 中引用 using Extensions;,删除无关代码后效果如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataProcessor
{
    using Extensions;
    class Program
    {
        public static int Main(string[] Args)
        {
              for (int CtrA = 0; CtrA <= 100; CtrA++)
              {
                    System.Diagnostics.Debug.Print((CtrA + 1).Ordinal);     // Error occurs here
              }
        }
    }
}

namespace Extensions
{
    public static class Extensions
    {
        public static string Ordinal(int Number)
        {
            string Str = Number.ToString();
            Number = Number % 100;
            if ((Number >= 11) && (Number <= 13))
            {
                Str += "th";
            }
            else
            {
                switch (Number % 10)
                {
                    case 1:
                        Str += "st";
                        break;
                    case 2:
                        Str += "nd";
                        break;
                    case 3:
                        Str += "rd";
                        break;
                    default:
                        Str += "th";
                        break;
                }
            }
            return Str;
        }
    }

我在行 System.Diagnostics.Debug.Print((CtrA + 1).Ordinal); 以及我将 .Ordinal 用作 int 方法的其他任何地方遇到编译时错误,指出:

'int' 不包含 'Ordinal' 的定义并且没有扩展方法 'Ordinal' 可以找到接受类型 'int' 的第一个参数(您是否缺少使用指令或程序集引用?)

谁能告诉我我做错了什么?

您必须在任何参数之前添加 this

public static string Ordinal(this int Number)

他们的第一个参数指定了该方法操作的类型,参数前面有this修饰符。仅当您使用 using 指令将命名空间显式导入源代码时,扩展方法才在范围内。

您的方法不是扩展方法。它在第一个参数之前错过了 this

public static string Ordinal(this int Number)

Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier.

from Extension Methods (C# Programming Guide)

您需要像这样更改函数:

public static string Ordinal(this int Number)

注意 this 关键字。当您拥有的功能是扩展时,这是必需的。

你忘了这个。

namespace Extensions
{
    public static class Extensions
    {
        public static string Ordinal(this int Number)
        {
            string Str = Number.ToString();
            Number = Number % 100;
            if ((Number >= 11) && (Number <= 13))
            {
                Str += "th";
            }
            else
            {
                switch (Number % 10)
                {
                    case 1:
                        Str += "st";
                        break;
                    case 2:
                        Str += "nd";
                        break;
                    case 3:
                        Str += "rd";
                        break;
                    default:
                        Str += "th";
                        break;
                }
            }
            return Str;
        }
    }