如何使用可选参数调用委托?

时间:2017-06-05 20:34:33

标签: c# .net delegates

我有以下内容:

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();

1 个答案:

答案 0 :(得分:0)

您可以使用委托方法中的可选参数来实现您正在寻找的内容,并通过Invoke方法传递参数。之前的答案显示了如何做到这一点:Can a Delegate have an optional parameter?