【问题标题】:Type inference fail类型推断失败
【发布时间】:2014-02-24 18:35:49
【问题描述】:

我有以下类型推断“失败”的情况(至少我希望它失败了)。基本上,我有一个接受泛型数组的方法。我需要为匿名对象键入该数组,但类型推断无法这样做。

    private void foo<T>(IEnumerable<T> items, Func<T, Object>[] propertySelector) { }

    public void Main()
    {
        var peeps = new[]
        {
            new {FirstName = "Taco", LastName = "King"},
            new {FirstName = "Papa", LastName = "Georgio"}
        };

        foo(peeps, new[]
        {
            an => an.FirstName, //Error cannot infer type of "an"
            an => an.LastName   //Error cannot infer type of "an"
        });
    }

我认为原因是数组类型是从其内容而非上下文推断出来的。看起来这使得在这种情况下使用匿名类型变得不可能。

有什么办法解决这个问题吗?

【问题讨论】:

    标签: c# type-inference


    【解决方案1】:

    在给出的示例中,您可以将propertySelector 更改为params 参数,然后单独传入每个函数而不是作为数组传入。如果你因为某种原因不能使用params,那么像这样的辅助函数就可以了:

        /// <summary>
        /// Allows the use of type inference to get selector functions for the type of an enumerable.
        /// </summary>
        /// <typeparam name="T">The type of the enumerable.</typeparam>
        /// <param name="enumerable">The enumerable.</param>
        /// <param name="selectors">A set of selectors to return.</param>
        /// <returns>The selectors passed in.</returns>
        public static Func<T, Object>[] GetSelectors<T>(
            IEnumerable<T> enumerable,
            params Func<T, Object>[] selectors)
        {
            return selectors;
        }
    

    所以你的例子会变成:

    private void foo<T>(IEnumerable<T> items, Func<T, Object>[] propertySelector) { }
    
    public void Main()
    {
        var peeps = new[]
        {
            new {FirstName = "Taco", LastName = "King"},
            new {FirstName = "Papa", LastName = "Georgio"}
        };
    
        foo(peeps, GetSelectors(peeps, an => an.FirstName, an => an.LastName));
    }
    

    【讨论】:

    • 您只是问了一个问题,以便您自己回答吗?
    • 是的 wt*,马上就回答了。我认为这家伙有 2 个帐户,只是用另一个帐户回答自己以获得点......蹩脚
    • @AnnArbor87 我有一个帐户,是的,我回答了我自己的问题。不,我不是为了积分。如果你曾经问过一个问题,你会在这里看到它的一个选项。我自己回答了这个问题,以帮助我记住这一点以备不时之需,以防它可能对其他人有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多