【问题标题】:How to invoke a delegate with optional params?如何使用可选参数调用委托?
【发布时间】:2017-06-05 20:34:32
【问题描述】:

我有以下:

var availableDelegates = new Dictionary<string, SampleHandler>{
    {"TestWithNoParams", SampleHandlerOne }, // this is what I have now - working
    {"TestWithParamSetA", SampleHandlerTwo } // need this
    {"TestWithNoParams", SampleHandlerTwo } // and this - working
}

public static SampleHandler SampleHandlerOne(){
     // do stuff - working
}

// v1
public static SampleHandler SampleHandlerTwo(){
     // do stuff without parameters - working
}

// v2
public static SampleHandler SampleHandlerTwo(HandlerTwoParams params = null) { // trying to update to support optional params
     // do stuff with parameters - not working
     // params.Foo = bar
}

如何将可选参数传递给委托?我的想法是我可以做到:

if (someCondition)
    availableDelegates[target].Invoke(optionalParams);
else
    availableDelegates[target].Invoke();

【问题讨论】:

  • SampleHandler 似乎没有可选参数。所以这行不通。
  • @HansPassant - 这就是代码中出现v1v2 的原因。

标签: c# .net delegates


【解决方案1】:

您可以使用委托方法上的可选参数,通过Invoke 方法传递参数,从而准确实现您正在寻找的东西。这个先前的答案显示了如何做到这一点:Can a Delegate have an optional parameter?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2023-04-04
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    相关资源
    最近更新 更多