簡體   English   中英

使用擴展方法而不調用類名

[英]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;

鏈接

這不是一種擴展方法。 您沒有定義作為擴展方法基礎的對象(您使用this方法執行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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM