部分类型推断 [英] Partial type inference

查看:139
本文介绍了部分类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的(简本)的通用方法:

 公共静态TResult PartialInference< T,TResult>(Func键< T,TResult>的行动,对象参数)
{
    返回动作((T)参数);
}

在上面,参数是故意键入对象的。这是要求的一部分。

当我填写的类型,我可以调用它是这样的:

  VAR测试1 = PartialInference<字符串,布尔>(
    P => p.EndsWith(!),世界,你好!
);

不过,我想使用类型推断。 preferably,我想这样写:

  VAR测试2 = PartialInference<串GT;(
    P => p.EndsWith(!),世界,你好!
);

但是,这并不编译。我想出了最好的是这样的:

  VAR TEST3 = PartialInference(
    (串P)=> p.EndsWith(!),世界,你好!
);

我想之所以有此作为一个类型参数,仍然有键入正确的返回类型是因为我的实际调用看起来是这样的:

  VAR list1的= ComponentProvider.Perform(
    (ITruckSchedule_StaffRepository P)=> p.GetAllForTruckSchedule(本)

这是非常丑陋的,我也爱写的东西是这样的:

  VAR列表2 = ComponentProvider.Perform< ITruckSchedule_StaffRepository>(
    P => p.GetAllForTruckSchedule(本)


解决方案

您可以T分割成一个通用的方法对泛型类型:

 类Foo< TOuter> {
    公共静态无效的酒吧和LT; TINNER>(ARG TINNER){...}
}
...
INT X = 1;
美孚<串GT; .BAR(X);

下面的INT推断,但字符串是明确的。

I have a generic method like this (simplified version):

public static TResult PartialInference<T, TResult>(Func<T, TResult> action, object param)
{
    return action((T)param);
}

In the above, param is of type object on purpose. This is part of the requirement.

When I fill in the types, I can call it like this:

var test1 = PartialInference<string, bool>(
    p => p.EndsWith("!"), "Hello world!"
);

However, I'd like to use type inference. Preferably, I would like to write this:

var test2 = PartialInference<string>(
    p => p.EndsWith("!"), "Hello world!"
);

But this does not compile. The best I came up with is this:

var test3 = PartialInference(
    (string p) => p.EndsWith("!"), "Hello world!"
);

The reason I would like to have this as a type parameter and still have the correctly typed return type is because my actual calls look something like this:

var list1 = ComponentProvider.Perform(
    (ITruckSchedule_StaffRepository p) => p.GetAllForTruckSchedule(this)
)

Which is very ugly and I would love to write as something like this:

var list2 = ComponentProvider.Perform<ITruckSchedule_StaffRepository>(
    p => p.GetAllForTruckSchedule(this)
)

解决方案

You can split t into a generic method on a generic type:

class Foo<TOuter> {
    public static void Bar<TInner>(TInner arg) {...}
}
...
int x = 1;
Foo<string>.Bar(x);

Here the int is inferred but the string is explicit.

这篇关于部分类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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