如何从 C# 扩展方法中访问“this"? [英] How do I access 'this' from within a C# extension method?

查看:55
本文介绍了如何从 C# 扩展方法中访问“this"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 Vector2 和 XNA,我发现在零向量上调用 Normalize() 成员函数会将其规范化为 {NaN, NaN} 向量.这一切都很好,但就我而言,我更喜欢将它们保留为零向量.

I've been working with Vector2's and XNA, and I've come to find that calling the Normalize() member function on a Zero Vector normalizes it to a vector of {NaN, NaN}. This is all well and good, but in my case I'd prefer it instead just leave them as Zero Vectors.

将此代码添加到我的项目中启用了一个可爱的扩展方法:

Adding this code to my project enabled a cute extension method:

using ExtensionMethods;

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static Vector2 NormalizeOrZero(this Vector2 v2)
        {
            if (v2 != Vector2.Zero)
                v2.Normalize();
            return v2;
        }
    }
}

不幸的是,这个方法返回归一化的向量,而不是简单地归一化我用来调用这个扩展方法的向量.我想改为像 vector2Instance.Normalize() 那样行事.

Unfortunately, this method returns the normalized vector, rather than simply normalizing the vector which I use to invoke this extension method. I'd like to to instead behave as vector2Instance.Normalize() does.

除了使这个无效之外,我如何调整它以便修改v2"?(本质上,我需要访问this"对象,或者我需要通过引用传递v2".)

Aside from making this void, how do I adjust this so that the 'v2' is modified? (Essentially, I need access to the 'this' object, or I need 'v2' to be passed by reference.)

是的,我试过了:

    public static void NormalizeOrZero(this Vector2 v2)
    {
        if (v2 != Vector2.Zero)
            v2.Normalize();
    }

不行,v2只是NormalizeOrZero范围内的一个变量.

Doesn't work, v2 is just a variable in the scope of NormalizeOrZero.

推荐答案

这不起作用,因为 Vector 2 实际上是一个结构体.这意味着它是按值传递的,您不能修改调用者的副本.我认为你能做的最好的事情是 lomaxxx 指定的解决方法.

This doesn't work because Vector 2 is actually a struct. This means it gets passed by value and you can't modify the caller's copy. I think the best you can do is the workaround specified by lomaxxx.

这说明了为什么您通常应该避免使用结构.有关详细信息,请参阅此问题.Vector2 违反了结构应该是不可变的准则,但在 XNA 的上下文中这样做可能是有意义的.

This illustrates why you should generally avoid using structures. See this question for more information. Vector2 violates the guideline that structs should be immutable, but it probably made sense to do so in the context of XNA.

这篇关于如何从 C# 扩展方法中访问“this"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆