Created
February 12, 2021 17:38
-
-
Save chrisyarbrough/d20bbbc0419198ffb7b24448f7bc983d to your computer and use it in GitHub Desktop.
Be careful when refactoring lambdas with method groups. The method group may seem cleaner but it also breaks virtual methods by only calling the base implementation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using DG.Tweening; | |
| using Nementic.Exit; | |
| using UnityEngine; | |
| public class VirtualDelegateInvocation : MonoBehaviour | |
| { | |
| private Child p = new Child(); | |
| [EditorButton()] | |
| void Do() | |
| { | |
| p.Close(); | |
| } | |
| } | |
| public class Parent | |
| { | |
| public void Close() | |
| { | |
| // Close instantly: | |
| //OnClose(); | |
| // Or defer to later: | |
| var sequence = DOTween.Sequence(); | |
| sequence.AppendInterval(1f); | |
| sequence.onComplete += OnClose; | |
| // So far this works. | |
| // Refactor: | |
| Do(OnClose); | |
| } | |
| private void Do(Action callback) | |
| { | |
| var sequence = DOTween.Sequence(); | |
| sequence.AppendInterval(1f); | |
| // Child and base implementations are called. | |
| sequence.onComplete += () => callback(); | |
| // Ups, broken, only the base class is called. | |
| sequence.onComplete += callback.Invoke; | |
| } | |
| protected virtual void OnClose() | |
| { | |
| Debug.Log("Base"); | |
| } | |
| } | |
| public class Child : Parent | |
| { | |
| protected override void OnClose() | |
| { | |
| Debug.Log("Child"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment