Last active
August 29, 2015 13:58
-
-
Save EifelMono/10018411 to your computer and use it in GitHub Desktop.
ClassHelper for Initialization and Finalization calls of a class
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
using System; | |
using System.Reflection; | |
namespace Utils | |
{ | |
[AttributeUsage(AttributeTargets.Method)] | |
public sealed class InitializationAttribute : Attribute | |
{ | |
public InitializationAttribute() | |
{ | |
} | |
} | |
[AttributeUsage(AttributeTargets.Method)] | |
public sealed class FinalizationAttribute : Attribute | |
{ | |
public FinalizationAttribute() | |
{ | |
} | |
} | |
/// <summary> | |
/// public class Test | |
/// { | |
/// [Initialization] | |
/// public void Begin() | |
/// { | |
/// Console.WriteLine("Begin"); | |
/// } | |
/// | |
/// [Finalization] | |
/// public static void End() | |
/// { | |
/// Console.WriteLine("End"); | |
/// } | |
/// | |
/// Anywhere at the begin of the program | |
/// ClassHelper.Initialization(); | |
/// | |
/// if finished | |
/// ClassHelper.Finalization(); | |
/// </summary> | |
public sealed class ClassHelper | |
{ | |
private static void CallByName(Type attributeType) | |
{ | |
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) | |
{ | |
foreach (Type type in assembly.GetTypes()) | |
{ | |
string typeNameSpace = type.Namespace; | |
if (!string.IsNullOrEmpty(typeNameSpace)) | |
{ | |
if (type.IsClass) | |
foreach (MethodInfo method in type.GetMethods()) | |
if (method.GetCustomAttributes(attributeType, false).Length > 0) | |
method.Invoke(null, null); | |
} | |
} | |
} | |
} | |
public static void Initialization() | |
{ | |
CallByName(typeof(InitializationAttribute)); | |
} | |
public static void Finalization() | |
{ | |
CallByName(typeof(FinalizationAttribute)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment