C#方法组类型推断 [英] C# method group type inference

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

问题描述

  class MyClass { 
public int Method(float arg)=> 0;
}

TResult Call< T1,TResult>(Func< T1,TResult> func)=>
func(默认(T1));

void Main()
{
var m = new MyClass();
var r1 =调用< float,int>(m.Method);
var r2 =调用(m.Method); // CS0411
}

最后一行无法使用 CS0411



用例:使用AutoFixture生成函数调用参数。

解决方案

不幸的是,这是C#中类型推断的限制。它对于返回类型并没有什么太大的作用,在你的情况下需要这些来完全推断 Call<> 的泛型参数。


I'm trying to write a generic method that supplies parameters and calls a function, like this:

class MyClass {
    public int Method(float arg) => 0;
}

TResult Call<T1, TResult>(Func<T1, TResult> func) =>
    func(default(T1));

void Main()
{
    var m = new MyClass();
    var r1 = Call<float, int>(m.Method);
    var r2 = Call(m.Method); // CS0411
}

The last line fails to compile with CS0411. Is there any workaround to get type inference to work here?

Use case: using AutoFixture to generate function call parameters.

解决方案

Unfortunately no, that's a limitation of type inference in C#. It doesn't really do much with return types, which is what's needed in your case to fully infer the generic arguments to Call<>.

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

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