【发布时间】:2015-08-06 21:49:19
【问题描述】:
我在方法中使用委托参数。我想提供一个与委托签名匹配的重载方法。该类如下所示:
public class Test<DataType> : IDisposable
{
private readonly Func<string, DataType> ParseMethod;
public Test(Func<string, DataType> parseMethod)
{
ParseMethod = parseMethod;
}
public DataType GetDataValue(int recordId)
{
// get the record
return ParseMethod(record.value);
}
}
然后我尝试使用它:
using (var broker = new Test<DateTime>(DateTime.Parse))
{
var data = Test.GetDataValue(1);
// Do work on data.
}
现在DateTime.Parse 有一个与Func 匹配的签名;但是,因为它被重载,编译器无法解析使用哪个方法;在后网站上似乎很明显!
然后我尝试了:
using (var broker = new Test<DateTime>((value => DateTime.Parse(value))))
{
var data = Test.GetDataValue(1);
// Do work on data.
}
有没有一种方法可以指定正确的方法,而无需编写简单地调用 DateTime.Parse 的自定义方法?
【问题讨论】:
标签: c# generics delegates overloading