I have a boolean function which is used in the decision-making of many other functions. And every time, the user is either given a message box or allowed to proceed, depending on the return value of that function. So my pseudo-code might look like this:
private bool IsConsented()
{
//some business logic
}
private void NotReal()
{
if (IsConsented())
{
//call function A
}
else
{
MessageBox.Show("Need consent first.");
}
}
private void NotReal2()
{
if (IsConsented())
{
//call function B
}
else
{
MessageBox.Show("Need consent first.");
}
}
I am looking for a simpler way to do this, rather than hard-coding that if-else logic into every single function of mine. I'd like to be able to have a function like:
private void CheckConsent(function FunctionPointer)
{
if (IsConsented())
{
//call the function
FunctionPointer();
}
els开发者_StackOverflow中文版e
{
MessageBox.Show("Need consent first.");
}
}
So that I can just pass a pointer to a function. I have a real suspicion that this has to do with delegates, but I don't know the syntax, and I don't understand how to pass parameters around using delegates.
You need to declare the delegate (or use a built-in one, such as Action):
private void CheckConsent(Action action)
{
if (IsConsented())
{
action();
}
else
{
MessageBox.Show("Need consent first.");
}
}
You could then do:
private void NotReal()
{
this.CheckConsent( () =>
{
// Do "NotReal" work here...
});
}
Reed Copsey way of doing is clean one. It uses the Action delegate already defined along with lambda expression. But if you are not comfortable with that here is the old way of doing .
private delegate void realDelegate();
realDelegate d = new realDelegate(NotReal);
You can now call
private void CheckConsent(realDelegate d)
{
if(d !=null)
d();
}
精彩评论