My Development Notes

By Haemoglobin
3/10/2010 (revision 1)

Reflection

Assembly.Load(assmeblyName); //usually from the GAC
Assembly.LoadFile(fileName); 
Assembly.LoadFrom(filePath); 
Assembly.ReflectionOnlyLoad(); //Allows you to examine the assembly but not create instances of types or run methods.
Assembly.ReflectionOnlyLoadFrom();

Type t = Assembly.GetType(); //after loading an assembly
ConstructorInfo ci = t.GetConstructor(new Type[] { typeof(string) });
Object sb = ci.Invoke(new Object[] { "Hello, "}); 
MethodInfo sbAppend = t.GetMethod("Append", new Type[] { typeof(string) });
Object result = sbAppend.Invoke(sb, new object[] { "world!" });
result.ToString(); 

PropertyInfo lengthProperty = t.GetProperty("Length"); 
int length = (int)lengthProperty.GetValue(sb, null); 

MemberInfo[] mi = t.GetMembers(BindingFlags.NonPublic | BindingFlags.[Static | DeclaredOnly | FlattenHierarchy | IgnoreCase | Instance | Public]); 
foreach (MemberInfo m in mi) {
    m.Name, .MemberType
}

foreach(Attribute attr in Assembly.GetExcecutingAssembly().GetCustomAttributes(false)) {
    if (attr.GetType() == typeof(AssemblyCopyrightAttribute)) { //or (attr is AssemblyCopyrightAttribute)
        ((AssemblyCopyrightAttribute)attr).Copyright
    }
}
//or 
(AssemblyDescriptionAttribute)Assembly.GetExcecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false)[0]).Copyright;

MethodInfo Properties

Dynamically generating assemblies

AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("dynAssembly"), AssemblyBuilderAccess.RunAndSave); 
ModuleBuilder bm = ab.DefineDynamicModule("dynMod"); 
TypeBuilder tb = mb.DefineType("dynType", TypeAttributes.Class | TypeAttributes.Public); 
ConstructorBuilder cb = tb.DefineDefaultConstructor(MethodAttributes.Public); 
MethodBuilder method = tb.DefineMethod("Greet", MethodAttributes.Public | MethodAttributes.Static);
ILGenerator dynCode = method.GetILGenerator(); 
dynCode.EmitWriteLine("Hello, world!"); 
dynCode.Emit(OpCodes.Ret); 
Type myDynType = tb.CreateType(); 
myDynType.GetMethod("Greet").Invoke(null, null); 

Comments

Powered by BlogEngine.NET 1.6.1.0 | Design by styleshout | Enhanced by GravityCube.net | 1.4.5 Changes by zembian.com | Adapted by HamishGraham.NET
(c) 2010 Hamish Graham. Banner Image (c) Chris Gin