明确指定Lambda参数类型

时间:2018-09-22 09:36:18

标签: c# lambda

我对Lambda表达式有一点问题。我不理解C#编写的本示例。如何使用有趣的论点?您能给我解释一下还是举一些其他例子?我将非常感谢。

代码如下:

using System;

public class Program
{
    static void Main()
    {
        Bar((int x) => Foo(x));
    }

    static void Foo<T>(T x)
    {
        Console.WriteLine(x);
    }

    static void Bar<T>(Action<T> fun)
    {
        fun(5);     // Error: Cannot convert from int to T
    }
}

1 个答案:

答案 0 :(得分:0)

如果T是猫怎么办,如何将数字5转换为猫?没有任何意义

有些事情可能会更容易引起您的注意

static void Main()
{
    Bar(5, x => Foo(x));
    Bar("Bob", x => Foo(x));
}

static void Foo<T>(T x)
{
    Console.WriteLine(x);
}

static void Bar<T>(T somethingTangible, Action<T> fun)
{
    fun(somethingTangible); 
}

输出

5
Bob
相关问题