为什么不能推断这些泛型? [英] Why can't these generic types be inferred?

查看:86
本文介绍了为什么不能推断这些泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public static class CardView {
    public static object Column<TModel, TResult>(Func<TModel, TResult> field) {
        return null;
    }
}

public class Person 
{
    public string Name { get; set; }
    public bool Gender { get; set; }
}

void Main()
{
    var model = new Person() { Name = "Andre", Gender = true };

    var b = CardView.Column(model => model.Name); // ERROR
    // The type arguments for method 'UserQuery.CardView.Column<TModel,TResult>(System.Func<TModel,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
}

由于某种原因,它无法推断Column方法的泛型类型.我要知道为什么我不能放弃类型推断并自己指定类型,因为这只是一个解决大问题的案例研究,而该问题将是必不可少的.

For some reason it's not able to infer the generic types for the Column method. I need to know why. I can't give up the type inference and specify the types myself because it's just a case study for a large problem where it will be indispensable.

编辑

我拼错了代码=/刚修复了它

I misspelled the code =/ just fixed it

推荐答案

为了使编译器执行类型推断,必须为其提供某种类型信息.在这种情况下,它提供的唯一信息是无类型的lambda表达式.编译器在这里真的没什么可做的.

In order for the compiler to perform type inference it has to be given some sort of type information. In this scenario the only information it's provided is an untyped lambda expression. The compiler really has nothing to go on here.

有两种方法可以解决此问题.最简单的方法是在lambda参数中添加类型

There are a couple of ways to resolve this. The easiest is to add a type to the lambda paramater

var b = CardView.Column((Person m) => m.Name);

这篇关于为什么不能推断这些泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆