代码之家  ›  专栏  ›  技术社区  ›  recursive

为什么不允许将此命名函数作为Func<>参数在C#中传递?

  •  2
  • recursive  · 技术社区  · 14 年前

    我很难理解在C#3.0中通过代表的规则是什么。决赛 .Max() 给出如下所示的编译错误,但我无法理解这种情况与其他任何情况之间的显著区别。

    int NamedIdentity(int val) { return val; }
    Func<int, int> Identity = x => x;
    
    void Main() {
        var range = Enumerable.Range(1, 10);
    
        range.Max();
        range.Max(x => x);
        range.Max(Identity);
        range.Max((Func<int, int>) NamedIdentity);
        range.Max(new Func<int, int>(NamedIdentity));
    
        // this line gives compile error
        range.Max(NamedIdentity); 
        /* The call is ambiguous between the following methods or properties: 
        * 'System.Linq.Enumerable.Max<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int,decimal>)' and 
        * 'System.Linq.Enumerable.Max<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int,decimal?>)'
        */
    }
    

    为什么不编译?我的理解是 NamedIdentity Func<int, int> ,所以它不需要浇铸,虽然很明显我错了。一个线索是编译错误正在讨论 Decimal 即使在代码的任何地方都没有引用。那是从哪里来的?函数引用不能隐式转换为具有相同签名的委托吗?

    1 回复  |  直到 14 年前