Not able to call theFunction using FUNC
protected void Page_Load(object sender, EventArgs e)
开发者_如何转开发{
int k = 0;
Func<int> p5 = () => { return k++; };
}
public int IntProducer()
{
return x++;
}
i am not able to call the function IntProducer(), is the syntax wrong ?
You were never able to call the function because you never attempted to call it directly or indirectly.
If you wanted to call it, first you must store function in the variable then call the variable like you would any other method.
protected void Page_Load(object sender, EventArgs e)
{
Func<int> producer = IntProducer; // store it
int result = producer(); // call it
}
Alternatively you could create a lambda function to call it too.
protected void Page_Load(object sender, EventArgs e)
{
Func<int> producer = () => IntProducer(); // store the lambda
int result = producer(); // call it
}
I'm not sure what you're actually trying to accomplish, but you don't need a Func<T>
to invoke a function. Just use this syntax:
protected void Page_Load(object sender, EventArgs e)
{
int k = IntProducer();
// Todo: Do more with k here
}
public int IntProducer()
{
return x++;
}
If you find you understand this really well, and feel you actually have a need for a Func<T>
, then you can just assign it, and call it like it were a normal function:
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++;
}
This is really only useful if you want to switch which method theFunc
points to while you're running, you want to pass it to another method, or you don't even want to bother naming IntProducer
, and just want to define it directly (like your lambda in your original code).
With the code in your question, I would throw out the lambda, and wouldn't bother with a Func<T>
. I'd just call IntProducer
directly, like the code at the top of my answer.
BTW, this is the lambda in your original code:
() => { return k; };
It basically works like an un-named function. In this case, that function takes no parameters.
精彩评论