using System; using System.Reflection; interface IMyInterface { void PrintAString(string s); void PrintAnInteger(int i); void PrintSomeNumbers(string desc, int i, double d); int GetANumber(string s); } public class MyClass : IMyInterface { public MyClass() { } public void PrintAString(string s) { Console.WriteLine("PrintAString: {0}", s); } public void PrintAnInteger(int i) { Console.WriteLine("PrintAnInteger: {0}", i); } public void PrintSomeNumbers(string desc, int i, double d) { Console.WriteLine("PrintSomeNumbers String: {0}", desc); Console.WriteLine("Integer: {0}", i); Console.WriteLine("Double: {0}", d); } public int GetANumber(string s) { Console.WriteLine("GetANumber: {0}", s); return 99; } public int DoItAll(string s, int i, double d) { IMyInterface mi = (IMyInterface)this; mi.PrintSomeNumbers(s, i, d); return mi.GetANumber(s); } } public class MainClass { public static void DoDynamicInvocation(string assembly) { Assembly a = Assembly.LoadFrom(assembly); foreach (Type t in a.GetTypes()) { if (t.IsClass == false) continue; if (t.GetInterface("IMyInterface") == null) continue; Console.WriteLine("Creating instance of class {0}", t.FullName); object obj = Activator.CreateInstance(t); object[] args = { "Dynamic", 1, 99.6 }; object result; result = t.InvokeMember("DoItAll",BindingFlags.Default|BindingFlags.InvokeMethod,null,obj,args); Console.WriteLine("Result of dynamic call: {0}", result); object[] args2 = { 12 }; t.InvokeMember("PrintAnInteger",BindingFlags.Default | BindingFlags.InvokeMethod,null,obj,args2); } } public static void Main(string[] args) { MyClass dmi = new MyClass(); dmi.PrintSomeNumbers("PrintMe", 1, 1.9); int i = dmi.GetANumber("GiveMeOne"); Console.WriteLine("I = {0}", i); DoDynamicInvocation(args[0]); } }
CurrentDomain, GetAssemblies
using System; using System.Reflection; using System.Globalization; class MainClass { public static void Main() { ListAssemblies(); string name1 = "System.Data, Version=2.0.0.0," +"Culture=neutral, PublicKeyToken=b77a5c561934e089"; Assembly a1 = Assembly.Load(name1); AssemblyName name2 = new AssemblyName(); name2.Name = "System.Xml"; name2.Version = new Version(2, 0, 0, 0); name2.CultureInfo = new CultureInfo(""); //Neutral culture. name2.SetPublicKeyToken(new byte[] {0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89}); Assembly a2 = Assembly.Load(name2); Assembly a3 = Assembly.Load("SomeAssembly"); Assembly a4 = Assembly.LoadFrom(@"c:sharedMySharedAssembly.dll"); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly a in assemblies) { Console.WriteLine(a.GetName()); } } }
System.Activator
using System; using System.Reflection; class AbstractFactory { public IReflect CreateObject(string classname) { IReflect objreflect; try { System.Type oType = System.Type.GetType(classname,true); objreflect = (IReflect)System.Activator.CreateInstance(oType); } catch(TypeLoadException e) { throw new InvalidOperationException("Type could " + "not be created. Check innerException " + "for details", e); } return objreflect; } }; public interface IReflect { string Name { get; } }; class Reflect1 : IReflect { public string Name { get { return "Reflect 1"; } } }; class Reflect2 : IReflect{ public string Name { get { return "Reflect 2"; } } } class AbstractFactoryApp { static void Main(string[] args) { callReflection(args[0]); } static void callReflection(string strClassName) { IReflect objReflect; AbstractFactory objFactory = new AbstractFactory(); try { objReflect = objFactory.CreateObject(strClassName); Console.WriteLine("You constructed a {0} object",objReflect.Name); } catch(Exception e) { Console.WriteLine("ERROR: {0} {1}", e.Message, (null == e.InnerException ? "" : e.InnerException.Message)); } } }
Use multiple where clauses
using System; // Gen has two type arguments and both have // a where clause. class Gen<T, V> where T : class where V : struct { T ob1; V ob2; public Gen(T t, V v) { ob1 = t; ob2 = v; } } class Test { public static void Main() { Gen<string, int> obj = new Gen<string, int>("test", 11); // The next line is wrong because bool is not // a reference type. // Gen<bool, int> obj = new Gen<bool, int>(true, 11); } }
Generic Queue
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Collections.ObjectModel; using System.Runtime.Serialization; public class Customer : System.IComparable { private int _id; private string _name; private string _rating; private static SortOrder _order; public enum SortOrder { Ascending = 0, Descending = 1 } public Customer(int id, string name) : this(id, name, "Other") { } public Customer(int id, string name, string rating) { this._id = id; this._name = name; this._rating = rating; } public int Id { get { return this._id; } set { this._id = value; } } public string Name { get { return this._name; } set { this._name = value; } } public string Rating { get { return this._rating; } set { this._rating = value; } } public static SortOrder Order { get { return _order; } set { _order = value; } } public override bool Equals(Object obj) { bool retVal = false; if (obj != null) { Customer custObj = (Customer)obj; if ((custObj.Id == this.Id) && (custObj.Name.Equals(this.Name) && (custObj.Rating.Equals(this.Rating)))) retVal = true; } return retVal; } public override string ToString() { return this._id + ": " + this._name; } public int CompareTo(Object obj) { switch (_order) { case SortOrder.Ascending: return this.Name.CompareTo(((Customer)obj).Name); case SortOrder.Descending: return (((Customer)obj).Name).CompareTo(this.Name); default: return this.Name.CompareTo(((Customer)obj).Name); } } } class Program { public static void Main(){ Queue<Customer> custQueue = new Queue<Customer>(100); custQueue.Enqueue(new Customer(99, "H", "P")); custQueue.Enqueue(new Customer(77, "B", "G")); custQueue.Enqueue(new Customer(55, "B", "S")); custQueue.Enqueue(new Customer(88, "B", "P")); Customer tmpCust = custQueue.Dequeue(); Console.Out.WriteLine("Dequeued: {0}", tmpCust); foreach (Customer cust in custQueue) Console.Out.WriteLine("Queue Item: {0}", cust); tmpCust = custQueue.Peek(); Console.Out.WriteLine("Queue Peek: {0}", tmpCust); custQueue.Enqueue(new Customer(88, "B", "P")); foreach (Customer cust in custQueue) Console.Out.WriteLine("Queue Item: {0}", cust); } }
Implement generic IEnumerable and IEnumerator
using System; using System.Threading; using System.Collections; using System.Collections.Generic; public class MyEnumerable<T> : IEnumerable<T> { public MyEnumerable( T[] items ) { this.items = items; } public IEnumerator<T> GetEnumerator() { return new NestedEnumerator( this ); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } // The enumerator definition. class NestedEnumerator : IEnumerator<T> { public NestedEnumerator( MyEnumerable<T> coll ) { Monitor.Enter( coll.items.SyncRoot ); this.index = -1; this.coll = coll; } public T Current { get { return current; } } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { if( ++index >= coll.items.Length ) { return false; } else { current = coll.items[index]; return true; } } public void Reset() { current = default(T); index = 0; } public void Dispose() { try { current = default(T); index = coll.items.Length; } finally { Monitor.Exit( coll.items.SyncRoot ); } } private MyEnumerable<T> coll; private T current; private int index; } private T[] items; } public class EntryPoint { static void Main() { MyEnumerable<int> integers = new MyEnumerable<int>( new int[] {1, 2, 3, 4} ); foreach( int n in integers ) { Console.WriteLine( n ); } } }
Implement generic IEnumerable
using System; using System.Collections; using System.Collections.Generic; public class MyColl<T> : IEnumerable<T> { private T[] items; public MyColl( T[] items ) { this.items = items; } public IEnumerator<T> GetEnumerator() { foreach( T item in items ) { yield return item; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class Test { static void Main() { MyColl<int> integers = new MyColl<int>( new int[] {1, 2, 3, 4} ); foreach( int n in integers ) { Console.WriteLine( n ); } } }