为接受 Func 作为参数的方法提供特定的重载方法

Providing an specific overloaded method to a method that accepts Func as parameter

我在方法中使用委托参数。我想提供一个匹配委托签名的重载方法。 class 看起来像这样:

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 的自定义方法的情况下指定正确的方法?

我认为你的第一个例子几乎是正确的。很难判断,因为缺少一些代码,但我认为问题在于编译器无法判断 record.value 是一个字符串——也许它是一个对象?如果是这样,将其转换为 GetDataValue 中的字符串应该会让编译器满意。

这是我试过的类似示例,编译后 运行 很好:

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