我有多种方法,它们具有两个可选参数,一个ConfigSourceType枚举和一个表示filePath的字符串,并返回“ IConfigFile”的实例(不同取决于配置文件)。
我正在尝试将这些方法作为Func传递,以便可以加载配置,但不能在没有参数的情况下调用委托。如果我使用Type.Missing,它仍然会抱怨缺少ConfigSourceType枚举。
编辑以包含代码:
DataHandler类:
public IConfigFile RetrieveMyConfiguration(
ConfigurationSourceType source = ConfigurationSourceType.Live,
string fileName = "")
{
/* Irrelevant */
return new ConfigFile();
}
主要的:
private void SomeMethod()
{
var dHandler = new DataHandler();
MyConfig = LoadConfigFile(dHandler.RetrieveMyConfiguration);
}
public IConfigFile LoadConfigFile(
Func<ConfigurationSourceType, string, IConfigFile> func)
{
IConfigFile configFile;
// Line below doesn't compile:
configFile = func.Invoke(null, Type.Missing);
return configFile;
}
您不能为指定可选参数Func<...>
,但可以为自己的委托指定参数。
此LINQPad示例显示了如何:
void Main()
{
var t = new Test(XYZ);
t();
t(15);
}
public delegate void Test(int a = 10);
public void XYZ(int a)
{
a.Dump();
}
输出:
10
15
但是,这意味着需要了解可选参数的是委托的接收端,但是似乎您想为方法指定委托并在发送端指定可选参数,或者从您包装在委托中的方法,除了创建匿名方法外,这是不可能的:
SomeMethod((a, b) => WrappedMethod(a, b, 42));
您可以执行以下操作:
public delegate void MyDelegate(int a, int b, int? c = null, int? d = null);
public void Method(int a, int b, int c = 10, int d = 42) { ... }
new MyDelegate((a, b, c, d) =>
{
if (c.HasValue && d.HasValue)
Method(a, b, c.Value, d.Value);
else if (c.HasValue)
Method(a, b, c.Value);
else if (d.HasValue)
Method(a, b, d: d.Value);
else
Method(a, b);
});
但是,这开始变得可笑了。
因此,不,您无法真正轻松地完成自己想要的事情。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句