无法使用FUNC调用函数

  • 本文关键字:调用 函数 FUNC c#-4.0
  • 更新时间 :
  • 英文 :

 protected void Page_Load(object sender, EventArgs e)
        {
            int k = 0;
            Func<int> p5 = () => { return k++; }; 
        }
 public int IntProducer()   
        {   
         return x++;   
        } 

我不能调用函数IntProducer(),是语法错误吗?

您无法调用该函数,因为您从未尝试直接或间接调用它。

如果你想调用它,首先你必须在变量中存储函数,然后像调用其他方法一样调用变量。

protected void Page_Load(object sender, EventArgs e)
{
    Func<int> producer = IntProducer; // store it
    int result = producer();          // call it
}

或者你也可以创建一个lambda函数来调用它。

protected void Page_Load(object sender, EventArgs e)
{
    Func<int> producer = () => IntProducer(); // store the lambda
    int result = producer();                  // call it
}

我不确定您实际上想要完成什么,但是您不需要Func<T>来调用函数。只需使用以下语法:

protected void Page_Load(object sender, EventArgs e)
{
    int k = IntProducer();
    // Todo: Do more with k here
}
public int IntProducer()   
{   
    return x++;   
}

如果你发现你真的很理解这个,并且觉得你实际上需要一个Func<T>,那么你就可以给它赋值,把它叫做就像它是一个正常的函数一样:

protected void Page_Load(object sender, EventArgs e)
{
    Func<int> theFunc = IntProducer;
    // Todo: Do some stuff here
    int k = theFunc(); // Calls `IntProducer`
    // Todo: Do more with k here
}
public int IntProducer()   
{   
    return x++;   
}

这是真正有用的,只有当你想切换哪个方法theFunc指向,而你正在运行,你想把它传递给另一个方法,或者你甚至不想打扰命名 IntProducer,只是想直接定义它(像你的lambda在你的原始代码)。

对于您问题中的代码,我会丢弃lambda,并且不会使用Func<T>。我只需要直接调用IntProducer,就像我的答案顶部的代码一样。

BTW,这是你原始代码中的lambda:

() => { return k; };

它基本上就像一个未命名的函数。在本例中,该函数不接受任何参数。

最新更新