// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Reflection; namespace E { public class StupidOne { public string F1; public string F2; public StupidOne(string f1, string f2) { F1 = f1; F2 = f2; } public override string ToString() { return F1 + " " + F2; } } public class StupidTwo { public string F1; public string F2; public StupidTwo(string f1, string f2) { F1 = f1; F2 = f2; } public override string ToString() { return F1 + " " + F2; } } public class SmartContain { private string f1; private string f2; public SmartContain(string f1, string f2) { this.f1 = f1; this.f2 = f2; } public SmartContain(object o) { if(o is StupidOne) { StupidOne xo = (StupidOne)o; f1 = xo.F1; f2 = xo.F2; } else if(o is StupidTwo) { StupidTwo xo = (StupidTwo)o; f1 = xo.F1; f2 = xo.F2; } else { throw new ArgumentException("Not a supported type: " + o.GetType().FullName); } } public string F1 { get { return f1; } set { f1 = value; } } public string F2 { get { return f2; } set { f2 = value; } } public override string ToString() { return f1 + " " + f2; } } public class SmartLink { private object o; private FieldInfo f1; private FieldInfo f2; public SmartLink(object o) { this.o = o; try { f1 = o.GetType().GetField("F1", BindingFlags.Public | BindingFlags.Instance); f2 = o.GetType().GetField("F2", BindingFlags.Public | BindingFlags.Instance); } catch { throw new ArgumentException("Not a supported type: " + o.GetType().FullName); } } public string F1 { get { return (string)f1.GetValue(o); } set { f1.SetValue(o, value); } } public string F2 { get { return (string)f2.GetValue(o); } set { f2.SetValue(o, value); } } public override string ToString() { return F1 + " " + F2; } } public class Program { public static void Main(string[] args) { StupidOne o1 = new StupidOne("A", "B"); StupidTwo o2 = new StupidTwo("C", "D"); SmartContain xo1 = new SmartContain(o1); SmartContain xo2 = new SmartContain(o2); SmartLink zo1 = new SmartLink(o1); SmartLink zo2 = new SmartLink(o2); Console.WriteLine(o1); Console.WriteLine(o2); Console.WriteLine(xo1); Console.WriteLine(xo2); Console.WriteLine(zo1); Console.WriteLine(zo2); xo1.F2 = "X"; xo2.F2 = "X"; Console.WriteLine(o1); Console.WriteLine(o2); Console.WriteLine(xo1); Console.WriteLine(xo2); Console.WriteLine(zo1); Console.WriteLine(zo2); zo1.F2 = "Z"; zo2.F2 = "Z"; Console.WriteLine(o1); Console.WriteLine(o2); Console.WriteLine(xo1); Console.WriteLine(xo2); Console.WriteLine(zo1); Console.WriteLine(zo2); } } }