【问题标题】:Extension method not found?找不到扩展方法?
【发布时间】:2018-10-31 13:56:49
【问题描述】:

所以在环顾四周并尝试自己纠正这个问题之后,我陷入了困境。我查看了以下帖子,并确保我已经包含了他们所说的所有程序集(我在来这里之前已经完成了,但仔细检查以确保):

在仔细检查了我的具有扩展名的文件以及尝试使用该扩展名的文件后;有没有其他可能的原因导致找不到扩展方法?

// Extension Class.
using SharpDX;
using SharpDX.Direct2D1;
namespace MyNamespace.Engine {
    public static class Utilities {
        public static Vector3 PointToNDC(this SpriteBatch sb, Size2 screenSize, Point p) {
            float x = 2.0f * p.X / screenSize.Width - 1.0f;
            float y = 1.0f - 2.0f * p.Y / screenSize.Height;
            return new Vector3(x, y, 0);
        }
    }
}

// Usage Class.
using MyNamespace.Engine;
using SharpDX;
using SharpDX.Direct2D1;
namespace MyNamespace.Prefabs {
    public class Sprite {
        public void Draw() {
            SpriteBatch.PointToNDC(new Size2(50, 50), new Point(0, 0));
        }
    }
}

注意

代码中的任何拼写错误都是实际的拼写错误,而不是代码本身。


更新

正如@Brian Rasmussen 在 cmets 中指出的那样,我没有从被扩展对象的实例中调用该方法。我还没有喝咖啡,所以很抱歉,至少这是一个简单的解决方法!

SpriteBatch sb = new SpriteBatch(...);
sb.PointToNDC(...); // <- Works.

【问题讨论】:

  • 我不确定您在问什么,但您没有将 PointToNDC 作为扩展方法调用。为此,您需要一个 SpriteBatch 的实例。
  • 您是否尝试在静态类上调用扩展?看起来您并没有尝试在 SpriteBatch 的实例上调用它
  • 您是否期望 `SpriteBatch.PointToNDC(new Size2(50, 50), new Point(0, 0));` 调用 public static Vector3 PointToNDC(this SpriteBatch sb, Size2 screenSize, Point p) { /*code*/}?它不会。您需要在 SpriteBatch 的实例上调用它:var sb = new SpriteBatch(); var v3 = sb.PointToNDC(/*params*/);
  • 由于您的 PointToNDC 甚至没有对 sb 参数做任何事情,因此将它作为扩展方法可能根本没有意义,而只是作为静态类上的常规静态方法.
  • @PerpetualJ:将其作为扩展方法仍然没有意义。您现在正在更新中创建一个丢弃的SpriteBatch,这样您就可以调用一个对SpriteBatch 的实例没有任何作用的扩展方法。对方法public static Vector3 PointToNDC(Size2 screenSize, Point p)进行签名并调用为Utilities.PointToNDC(...)

标签: c# extension-methods


【解决方案1】:

要调用PointToNDC 作为扩展方法,您需要一个SpriteBatch 的实例。

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    相关资源
    最近更新 更多