【问题标题】:C# generic delegate type inferenceC# 泛型委托类型推断
【发布时间】:2012-02-18 00:25:34
【问题描述】:

为什么 C# 编译器不能在指定示例中将 T 推断为 int?

void Main()
{
    int a = 0;
    Parse("1", x => a = x);
    // Compiler error:
    // Cannot convert expression type 'int' to return type 'T'
}

public void Parse<T>(string x, Func<T, T> setter)
{
    var parsed = ....
    setter(parsed);
}

【问题讨论】:

  • 我也无法推断。试试Parse&lt;int&gt;(...)
  • 解析方法的语法糖。我可以用表达式来做到这一点,但是我必须使用反射,这是不行的。
  • Expression 不是reflection。请显示您要执行的操作的完整代码。
  • @L.B 这正是我现在正在做的事情。但我想知道为什么编译器无法弄清楚,因为 'x => a = x' 返回一个 int。
  • @gdoron 我可以使用表达式来获取我要设置的属性的 PropertyInfo,但我必须使用反射来调用它。

标签: c# generics delegates


【解决方案1】:

对 lambda 的方法类型推断要求 lambda 参数的类型 在推断 返回 的类型之前已知。例如,如果你有:

void M<A, B, C>(A a, Func<A, B> f1, Func<B, C> f2) { }

还有一个电话

M(1, a=>a.ToString(), b=>b.Length);

那么我们会推断:

A is int, from the first argument
Therefore the second parameter is Func<int, B>. 
Therefore the second argument is (int a)=>a.ToString();
Therefore B is string.
Therefore the third parameter is Func<string, C>
Therefore the third argument is (string b)=>b.Length
Therefore C is int.
And we're done.

看,我们需要 A 来计算 B,B 来计算 C。在你的情况下,你想从... T 中计算出 T。而你不能那样做。

【讨论】:

  • 当你这样说时,它看起来真的很明显...... :)
【解决方案2】:

参见http://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx 泛型方法部分。

请注意,编译器无法根据类型推断类型 单独返回值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多