Reputation: 708
I am using a delegate parameter in a method. I would like to provide an overloaded method that matches the delegate signature. The class looks like this:
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);
}
}
Then I tried to use it:
using (var broker = new Test<DateTime>(DateTime.Parse))
{
var data = Test.GetDataValue(1);
// Do work on data.
}
Now DateTime.Parse
has a signature that matches the Func
; However, because it's overloaded, the compiler can't resolve which method to use; seems obvious in hind site!
I then tried:
using (var broker = new Test<DateTime>((value => DateTime.Parse(value))))
{
var data = Test.GetDataValue(1);
// Do work on data.
}
Is there a way to specify the correct method with out writing a custom method that simply calls the DateTime.Parse?
Upvotes: 0
Views: 81
Reputation: 704
I think your first example is almost correct. It's hard to tell because there's some missing code, but I believe the problem is that the compiler can't tell that record.value is a string--maybe it's an object? If so, casting it to a string inside GetDataValue should make the compiler happy.
Here's the similar example I tried, which compiled and ran fine:
class Test<X>
{
private readonly Func<string, X> ParseMethod;
public Test(Func<string, X> parseMethod)
{
this.ParseMethod = parseMethod;
}
public X GetDataValue(int id)
{
string idstring = "3-mar-2010";
return this.ParseMethod(idstring);
}
}
[TestMethod]
public void TestParse()
{
var parser = new Test<DateTime>(DateTime.Parse);
DateTime dt = parser.GetDataValue(1);
Assert.AreEqual(new DateTime(day: 3, month: 3, year: 2010), dt);
}
Upvotes: 1