First of all, sorry if this was asked before. I did a fairly comprehensive search and did not find anything, but maybe I missed something.
And now to the question: I'm trying to call the constructor through reflection, without luck. Basically, I have an object that I want to clone, so I'm looking for a copy constructor for its type, and then I want to call it. Here is what I have:
public Object clone(Object toClone) {
MethodBase copyConstructor = type.GetConstructor(
new Type[] { toClone.GetType() });
return method.Invoke(toClone, new object[] { toClone });
}
I call the above method as follows:
List<int> list = new List<int>(new int[] { 0, 1, 2 });
List<int> clone = (List<int>) clone(list);
Now notice that the invoke method that I use invokes MethodBaseinvoke. ConstructorInfoprovides an invoke method that works if called as follows:
return ((ConstructorInfo) method).Invoke(new object[] { toClone });
MethodBase, , , , , Dictionary<MethodBase>, Dictionary<ConstructorInfo>.
, , ConstructorInfo, , MethodBase . .
? .
Benjamin,
. , , ( "" )
class ClonerMethod {
public MethodBase method;
public bool isConstructor;
...
public Object invoke(Object toClone) {
return isConstructor ?
((ConstructorInfo) method).Invoke(new object[] { toClone }) :
method.Invoke(toClone, null);
}
}
ClonerMethod invoke , . , , , , Invoke ConstructorInfo MethodBase invoke, , , . , Func<,> , . Clone , , .
Func<,>, -, ( - ), . , , !:)