简体   繁体   English

Unity3D,如何为运营商编写扩展方法?

[英]Unity3D, how can I write an extension method for operators?

I am trying to extend Vector3 which is a Unity3D feature. 我试图扩展Vector3D功能的Vector3 It does not have a less than operator, so I am trying to create one. 它没有一个小于运算符,所以我试图创建一个。 However, When I write the extension method for it, my IDE tells me "Identifier expected, 'this' is a keyword". 但是,当我为它编写扩展方法时,我的IDE告诉我“Identifier expected,'this'是一个关键字”。

How can I write an extension method using operators? 如何使用运算符编写扩展方法? This is my attempt, which unexpectedly did not work: 这是我的尝试,出乎意料地无效:

using UnityEngine;
using System.Collections;

public static class Vector3Extensions
{
    public static bool operator <(this Vector3 vector3, Vector3 other)
    {
        if (vector3.x < other.x)
        {
            return true;
        }
        else if (vector3.x > other.x)
        {
            return false;
        }
        else if (vector3.y < other.y)
        {
            return true;
        }
        else if (vector3.y > other.y)
        {
            return false;
        }
        else if (vector3.z < other.z)
        {
            return true;
        }
        return false;
    }
}

You can not use extension method to overload on operator. 您不能使用扩展方法来重载运算符。 Perhaps you can add .LessThan . 也许你可以添加.LessThan

It's not extension methods but operator overloads. 它不是扩展方法,而是运算符重载。 See this MSDN documentation that states: 请参阅此MSDN文档 ,其中说明:

==, !=, <, >, <=, >= The comparison operators can be overloaded (but see note below). ==,!=,<,>,<=,> =比较运算符可以重载(但请参见下面的注释)。 Note The comparison operators, if overloaded, must be overloaded in pairs; 注意比较运算符如果过载,则必须成对过载; that is, if == is overloaded, != must also be overloaded. 也就是说,如果==超载,!=也必须重载。 The reverse is also true, and similar for < and >, and for <= and >=. 反之亦然,<和>以及<=和> =类似。

Complete documentation here . 完整文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM