Unity3D,如何为运算符编写扩展方法?
Unity3D, how can I write an extension method for operators?
我正在尝试扩展 Vector3,这是一个 Unity3D 功能。它没有小于运算符,所以我正在尝试创建一个。但是,当我为其编写扩展方法时,我的 IDE 告诉我 "Identifier expected, 'this' is a keyword".
如何使用运算符编写扩展方法?这是我的尝试,没想到没有成功:
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;
}
}
您不能使用扩展方法重载运算符。也许您可以添加 .LessThan
.
这不是扩展方法而是运算符重载。请参阅此 MSDN documentation,其中指出:
==, !=, <, >, <=, >= 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 >=.
完成文档here。
我正在尝试扩展 Vector3,这是一个 Unity3D 功能。它没有小于运算符,所以我正在尝试创建一个。但是,当我为其编写扩展方法时,我的 IDE 告诉我 "Identifier expected, 'this' is a keyword".
如何使用运算符编写扩展方法?这是我的尝试,没想到没有成功:
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;
}
}
您不能使用扩展方法重载运算符。也许您可以添加 .LessThan
.
这不是扩展方法而是运算符重载。请参阅此 MSDN documentation,其中指出:
==, !=, <, >, <=, >= 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 >=.
完成文档here。