0

考虑到在 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 时刻,上下文/场景/来源是什么?

4

2 回答 2

3

代表的目的是事件。将委托添加到事件的能力对我来说很有意义。

于 2012-06-21T18:35:42.727 回答
0

委托的目的是在代码中提供运行时分支点。

class Foo
{
    public void Method1()
    {
    }

    public SomeDelegateType Method2;
}

Method1 是一个固定的代码点,调用它总是会导致执行相同的代码(Method1 的主体)。Method2 是一个委托。您可以将委托视为“指向零个或多个方法的指针”。分配给委托的每个方法都按照添加的顺序调用。调用它的结果可以在运行时改变,因为可以随意添加/删除方法。

将委托视为“变量方法”的另一种方式。您使用变量来保存可以更改的值。您使用委托来保存可以更改的方法“地址”。我在这里松散地使用术语“地址”以保持答案简单。

添加

针对您的评论,如果我理解正确,您想知道如何指定委托类型。

必须定义委托类型,就像任何其他类型一样:

// define a delegate type that returns 'float' and accepts zero parameters
delegate float AMethodThatReturnsSingle();

// here is a method that accepts one of those as a parameter
float Method(AMethodThatReturnsSingle d)
{
    // call the passed in delegate and return its value
    return d();
}

.Net Framework 提供了许多对常见情况有用的委托类型。这是我们上面声明的使用通用Func<>委托类型的自定义委托的替代品:

float Method(Func<float> d)
{
    // call the passed in delegate and return its value
    return d();
}

Func 有多种形式来支持参数:

// Encapsulates a method that has no parameters and returns a value of the type
//     specified by the TResult parameter.
delegate TResult Func<TResult>();
// Encapsulates a method that has one parameter and returns a value of the type
//     specified by the TResult parameter.
delegate TResult Func<T, TResult>(T arg);
// Encapsulates a method that has two parameters and returns a value of the type
//     specified by the TResult parameter.
delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

还有Action<>一个不返回任何内容并采用您指定的类型的零个或多个参数(我相信最多定义四个)。

Predicate<>一个返回 bool 并采用您指定的类型的一个或多个参数。

还有普遍存在的EventHandler<T>,这是推荐用于事件的类型。

仅举几个。

于 2012-06-21T19:16:02.890 回答