I have this class to generate random objects:
public class Generator<T> { private Random rnd = new Random(); private List<Type> types = new List<Type>(); public Generator() { //can't a generic type constraint that says "implements any interface" so I use this ugly thing... if (!typeof(T).IsInterface) throw new Exception("Generator needs to be instanciated with an interface generic parameter"); types = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.GetInterfaces().Contains(typeof(T))).ToList(); } public T GetRandomObject() { int index = rnd.Next(types.Count); return (T)Activator.CreateInstance(types[index]); } public void SetNewGeneric<N>() { T = N; //this doesn't work... types = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.GetInterfaces().Contains(typeof(T))).ToList(); } } I use it like so:
Generator<IEnemy> generator = new Generator<IEnemy>(); var randomEnemy = generator.GetRandomObject(); //create and return randomly, any object that implements IEnemy... My question is, is there any way to change the type of T at runtime so I can do something like
generator.SetGeneric<IWeapon>(); var weapon = generator.GetRandomObject(); Any other ways I could do this if I'm taking the wrong path ?
Thanks.
generatoris no longer aGenerator<IEnemy>. How do you expect that to work, and how do you want to use that?