// 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 interface IBaseBusiness { T GetObject(); } public class Foo { public override string ToString() { return "I am a Foo"; } } public class Bar { public override string ToString() { return "I am a Bar"; } } public class FooBusiness : IBaseBusiness { public Foo GetObject() { return new Foo(); } } public class BarBusiness : IBaseBusiness { public Bar GetObject() { return new Bar(); } } public abstract class LazyLoadTest { protected abstract object GetBusinessObject(Type theType); public void TestLazyLoad(string typnam) { object business = GetBusinessObject(Type.GetType(typnam)); object something = business.GetType().InvokeMember("GetObject", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, business, new object[0]); Console.WriteLine(something); } } public class CompanyEntityTest : LazyLoadTest { protected override object GetBusinessObject(Type theType) { if(theType == typeof(Foo)) { return new FooBusiness(); } else if(theType == typeof(Bar)) { return new BarBusiness(); } else { throw new Exception("No Foo or Bar"); } } } public class Program { public static void Main(string[] args) { CompanyEntityTest cet = new CompanyEntityTest(); cet.TestLazyLoad("E.Foo"); cet.TestLazyLoad("E.Bar"); } } }