Type.MakeGenericType works great, thanks. Couple question about
MakeGenericType though. Is there a big performance hit for using
Type.MakeGenericType? Is the performance hit in calling
Type.MakeGenericType or when calling
Activator.CreateInstance(constructedType, ...)? Would something be gained
if I cached the Type output from the call to Type.MakeGenericType? I was
thinking something like this ...
private static Hashtable genericClassTypeCache = Hashtable.Synchronized(new
Hashtable());
private Type GetGenericClassType(Type classType, Type genericType)
{
string key = classType.ToString() + genericType.ToString();
if (genericClassTypeCache.Contains(key))
{
return (Type)genericClassTypeCache[key];
}
Type constructedType = classType.MakeGenericType(genericType);
genericClassTypeCache.Add(key, constructedType);
return constructedType;
}
thanks
Paul
[quoted text, click to view] "Oliver Sturm" <oliver@sturmnet.org> wrote in message
news:u9jSs%23nlFHA.3660@TK2MSFTNGP10.phx.gbl...
> Paul Welter wrote:
>> Is there anyway to do the following?
>>
>> Type myType = typeof(User);
>> Collection<myType> list = new Collection<myType>();
>>
>> I know I could just use User instead of myType but have a function that
>> takes a type and populates a collection then calls SetValue using
>> reflection. How would I create the generic collection to fill it and
>> call SetValue?
>
> You can do this:
>
> Type genericType = typeof(Collection<>);
> Type constructedType = genericType.MakeGenericType(myType);
>
> Now you can create an instance of the constructed type and call methods on
> it via Reflection:
>
> object myObject = Activator.CreateInstance(constructedType, ...);
> myObject.GetType().InvokeMember("SetValue", BindingFlags.Instance |
> BindingFlags.InvokeMethod | BindingFlags.Public,
> null, myObject, new object[] { ... });
>
> Now finally, let me say this: I'm quite sure there should be a better way
> to do whatever it is exactly that you want to do. Especially since the
> advent of Generics... Think about it, or tell us about it.
>
>
> Oliver Sturm
> --
> omnibus ex nihilo ducendis sufficit unum
> Spaces inserted to prevent google email destruction:
> MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
> ICQ 27142619
http://www.sturmnet.org/blog