Calling MethodBase's Invoke on a constructor (reflection)
Posted
by Alix
on Stack Overflow
See other posts from Stack Overflow
or by Alix
Published on 2010-03-30T08:17:50Z
Indexed on
2010/03/30
8:23 UTC
Read the original article
Hit count: 391
Hi everyone. First of all, sorry if this has been asked before. I've done a pretty comprehensive search and found nothing quite like it, but I may have missed something.
And now to the question: I'm trying to invoke a constructor through reflection, with no luck. Basically, I have an object that I want to clone, so I look up the copy constructor for its type and then want to invoke it. Here's what I have:
public Object clone(Object toClone) { MethodBase copyConstructor = type.GetConstructor( new Type[] { toClone.GetType() }); return method.Invoke(toClone, new object[] { toClone }); //<-- doesn't work }
I call the above method like so:
List list = new List(new int[] { 0, 1, 2 }); List clone = (List) clone(list);
Now, notice the invoke method I'm using is MethodBase
's invoke. ConstructorInfo
provides an invoke method that does work if invoked like this:
return ((ConstructorInfo) method).Invoke(new object[] { toClone });
However, I want to use MethodBase
's method, because in reality instead of looking up the copy constructor every time I will store it in a dictionary, and the dictionary contains both methods and constructors, so it's a Dictionary<MethodBase>
, not Dictionary<ConstructorInfo>
.
I could of course cast to ConstructorInfo
as I do above, but I'd rather avoid the casting and use the MethodBase
method directly. I just can't figure out the right parameters.
Any help? Thanks so much.
© Stack Overflow or respective owner