考虑到在 C# 中使用委托,有谁知道是否有性能优势或者是否方便程序员?如果我们正在创建一个包含方法的对象,听起来好像该对象将是内存中要调用的常量,而不是每次调用时都加载该方法。例如,如果我们查看以下基于 Unity3D 的代码:
public delegate H MixedTypeDelegate<G, H>(G g)
public class MainParent : MonoBehaviour // Most Unity classes inherit from M.B.
{
public static Vector3 getPosition(GameObject g)
{
/* GameObject is a Unity class, and Vector3 is a struct from M.B.
The "position" component of a GameObject is a Vector3. This method
takes the GameObject I pass to it & returns its position. */
return g.transform.position;
}
public static MixedTypeDelegate<GameObject, Vector3> PositionOf;
void Awake( ) // Awake is the first method called in Unity, always.
{
PositionOf = MixedTypeDelegate<GameObject, Vector3>(getPosition);
}
}
public class GameScript : MainParent
{
GameObject g = new GameObject( );
Vector3 whereAmI;
void Update( )
{
// Now I can say:
whereAmI = PositionOf(g);
// Instead of:
whereAmI = getPosition(g);
}
}
. . . 但这似乎是一个额外的步骤 - 除非有额外的小东西可以帮助。
我想问第二个问题的最简洁的方式是说:当你在理解代表时有你的 aha 时刻,上下文/场景/来源是什么?