Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用扩展方法而不调用类名_C#_Class_Extension Methods - Fatal编程技术网

C# 使用扩展方法而不调用类名

C# 使用扩展方法而不调用类名,c#,class,extension-methods,C#,Class,Extension Methods,我试图创建一个静态(全局)函数,我可以使用扩展方法从项目中的任何脚本中调用它,但我认为我没有正确地实现它 文件:extensions.cs namespace CustomExtensions { public static class MathExt { public static float Remap (float value, float from1, float to1, float from2, float to2) { return (((val

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

文件: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),否则我会得到一个错误

我还尝试使用CustomExtensions.MathExt但它仍然抛出了一个错误

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

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

using static CustomExtensions.MathExt;

这不是一种扩展方法。您没有定义作为扩展方法基础的对象(您可以使用
this
进行定义):

那么你叫它:

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

我想我可能做得不对。我怎么能像我的上一个示例所示,将其作为静态函数使用呢?那么该类应该是相同的,或者使用David的解决方案。尝试了一下,但它说
预期标识符,static是一个关键字
@ViperCode您使用的是什么版本的C#?它只适用于C#6(根据David的评论)@MatthewWatson认为这很可能是问题所在,我仍然使用.NET3.5,我相信这个项目还没有使用C#6,这就是它不起作用的原因。@ViperCode C#版本和.NET版本之间没有严格的联系。您可以将C#6与.Net3.5一起使用,但您需要Visual Studio 2015Ok找到信息,这是C#5,gunna查看为此而升级到C#6。我以为我做错了什么,但这只是版本的局限性。很高兴知道至少,谢谢!调用
MathExt.Remap(rpm,720,maxRPM,.75f,1.75f)时会出现哪些错误?@HimBromBeere I get
名称“Remap”在当前上下文中不存在
pitch = rpm.Remap(minRPM, maxRPM, 0.5f, 1.5f);