【问题标题】:Providing an specific overloaded method to a method that accepts Func as parameter为接受 Func 作为参数的方法提供特定的重载方法
【发布时间】: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


    【解决方案1】:

    我认为您的第一个示例几乎是正确的。很难说,因为缺少一些代码,但我认为问题在于编译器无法判断 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);
        }
    

    【讨论】:

      猜你喜欢
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多