Last active
March 31, 2023 18:25
-
-
Save nitinjs/10ce0ee2e377c88c8a9bde1ab9440336 to your computer and use it in GitHub Desktop.
golang defer keyword alternative in C#
This file contains 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
//Author: Nitin Sawant | |
//add reference to AspectInjector package https://github.com/pamidur/aspect-injector | |
using AspectInjector.Broker; | |
using System.Reflection; | |
DeferTest test = new DeferTest(); | |
test.Test(); | |
public class DeferTest | |
{ | |
[Deferrable] | |
public void Test() | |
{ | |
int i = 0; | |
Defer.Me(() => { Console.WriteLine("1"); }); | |
Defer.Me(() => { Console.WriteLine("2"); }); | |
i++; | |
Defer.Me(() => { Console.WriteLine("3"); }); | |
Defer.Me(() => { Console.WriteLine("4"); }); | |
if (i > 0) | |
return; | |
Defer.Me(() => { Console.WriteLine("5"); }); | |
} | |
} | |
#region DeferLib | |
[Aspect(Scope.Global)] | |
[Injection(typeof(DeferrableAttribute))] | |
public class DeferrableAttribute : Attribute | |
{ | |
[Advice(Kind.After)] | |
public void Executed([Argument(Source.Name)] string name) | |
{ | |
Defer.Execute(); | |
} | |
} | |
public class Defer | |
{ | |
private static Stack<Action> Actions { get; set; } | |
static Defer() { Actions = new Stack<Action>(); } | |
public static void Me(Action a) | |
{ | |
Actions.Push(a); | |
} | |
public static void Execute(Action action) | |
{ | |
action(); | |
Execute(); | |
} | |
public static void Execute() | |
{ | |
while (Actions.Count > 0) | |
{ | |
var a = Actions.Pop(); | |
a(); | |
} | |
} | |
} | |
#endregion |
Author
nitinjs
commented
Mar 31, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment