c# - 将方法分配给委托(delegate),其中委托(delegate)具有比方法更多的参数

标签 c# delegates

<分区>

我有一个委托(delegate),它需要很多参数,如下所示:

public delegate void MyDelegate(float thereAre, int lotsOf, string parametersIn, int thisDelegate);
public MyDelegate theDelegateInstance;

这很烦人,因为 Visual Studio 2010 没有任何类型的自动完成来帮助方法匹配委托(delegate)签名。我基本上希望能够编写一个方法,该方法只接受委托(delegate)的部分(或不接受)参数,而忽略其他参数,因为它根本不使用它们。

theDelegateInstance += delegate()
{
    Debug.Log("theDelegateInstance was called");
};

或者

theDelegateInstance += delegate(float thereAre, int lotsOf)
{
    if(thereAre > lotsOf) Debug.Log("thereAre is way too high");
};

我发现我可以让一个方法接受一个委托(delegate)返回一个 MyDelegate 并像这样调用它:

public delegate void VoidMethod();

public static MyDelegate ConvertToMyDelegate(VoidMethod method)
{
    return delegate(float thereAre, int lotsOf, string parametersIn, int thisDelegate)
    {
        method();
    };
}

但这需要我为每个不同的转换声明一个静态方法。

我刚刚发现我可以在没有任何参数的情况下完成我的第一个示例来达到预期的结果:

theDelegateInstance += delegate//Notice that there are no brackets here.
{
    Debug.Log("theDelegateInstance was called");
};

但这只适用于不带参数的内联方法。如果我想像第二个示例那样使用其中一个参数,我将需要拥有所有这些参数。

最佳答案

你总是可以用 lambda 来做。

您可以通过两种方式实现 - 使用您要调用的两个示例函数:

第一种方式 - 创建方法,并直接调用它:

void FirstFunction(float thereAre, int lotsOf)
{
    if(thereAre > lotsOf) 
        Debug.Log("thereAre is way too high");
}

并以这种方式调用它:

theDelegateInstance += (t, l, p, td) => FirstFunction(t, l);

第二种方式 - 直接调用而不创建函数:

theDelegateInstance += 
    (t, l, p, td) => Debug.Log("theDelegateInstance was called");

关于c# - 将方法分配给委托(delegate),其中委托(delegate)具有比方法更多的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16968546/

相关文章:

c# - Linq ExecuteCommand 不理解空值

c# - 查找数组之间匹配项数量的最快方法是什么?

c# - 如何将这两个方法变成委托(delegate)调用?

C# 委托(delegate)问题 - 这段代码到底做了什么?

c# - 在 C# 中绑定(bind)到 DataGridView 时使用的一个很好的集合

javascript - 使用jquery查找中继器复选框选中的值

c# - 如何禁用 Telerik GridView 行中的特定单元格

swift - 委托(delegate)的函数返回 nil

kotlin - Kotlin 内置的 "lazy"函数是如何工作的?

c++ - 如何制作Qt委托(delegate)编辑器 'sticky'