使用扩展方法而不调用 class 名称

Using an extension method without calling class name

我正在尝试创建一个静态(全局)函数,我可以使用扩展方法从项目中的任何脚本中调用它,但我认为我没有正确实现它。

文件:extensions.cs

namespace CustomExtensions
{
  public static class MathExt
  {
    public static float Remap (float value, float from1, float to1, float from2, float to2)
    {
      return (((value - from1) * (to2 - from2) / (to1 - from1)) + from2);
    }
  }
}

现在我希望能够在另一个文件中使用此语法:

using CustomExtensions;

public class MySound
{
  public void SetPitch(float rpm)
  {
    pitch = Remap(rpm, minRPM, maxRPM, 0.5f, 1.5f);
  }
}

但是我得到一个错误,除非我这样做 MathExt.Remap(rpm, 720, maxRPM, .75f, 1.75f);

我也试过using CustomExtensions.MathExt;,但还是报错。

我想调用这个函数而不必在它之前声明 MathExt。我意识到只需添加类名就足够简单了,但我想了解我做错了什么。

如果您使用的是 C#6,您可以尝试使用

using static CustomExtensions.MathExt;

Link

那不是扩展方法。您没有定义作为扩展方法基础的对象(您使用 this 来定义):

public static float Remap (this float value, float from1, float to1, float from2, float to2)
{ }

然后你称它为:

pitch = rpm.Remap(minRPM, maxRPM, 0.5f, 1.5f);