views:

1168

answers:

3

In the following example i can create an object dynamically via a string; however, i have no way to get at the public methods of BASE class. i can't cast obj to a BASE because i don't know what generic will be used at design time. any suggestings on doing so at runtime would be nice.

Project A contains Class A{T,J> : BASE{T,J>
Project B contains Class B{T,J> : BASE{T,J>

Project C contains Class BASE{T,J>
public virtual control{T,J> item

Project Windows Form
cmdGo_Click event

string dll = textbox1.text //ex "ProjectA.dll"
string class = textbox2.text //ex "A`2[enuT,enuJ]"
object obj = activator.createinstancefrom(dll,class)

+1  A: 

If you do not know the type parameters used at run-time, then you cannot use any operations that depend on these types either, so... why not make a non-generic base class to BASE that contains all the operations that do not depend on the generic parameters, then you can case obj to that base type and use it.

jerryjvl
i know the parameters at runtime as they are stated in the textbox A`2[enuT,enuJ]. unfortunately my public control{T,J> is a must. I think i may be out of luck. Thanks for your help
alpha
A: 

At runtime the generics part of the equation does not matter, because the compiler has already filled in the gaps for the generic implementation. I believe you can use reflection to get at the base class methods, like in this example below, I hope this helps.

MethodInfo[] baseMethods = obj.GetType().BaseType.GetMethods();
object retObj = baseMethods[0].Invoke(obj, new object[] {"paramVal1", 3, "paramVal3"});
James
+1  A: 

This code creates an instance of BASE<int, string> :

Type type = typeof(BASE<,>).MakeGenericType(typeof(int), typeof(string));
object instance = Activator.CreateInstance(type);
Thomas Levesque
problem with that is you know the generics at design time (typeof(int), typeof(string), i don't have that luxury.
alpha