C# constructing generic method [duplicate]
var leftCurrent = leftArray.GetValue(i);
var rightCurrent = rightArray.GetValue(i);
var mi = typeof (PropertyCompare).GetMethod("NotEqualProperties");
mi.MakeGenericMethod(leftCurrent.GetType());
var notEqualProps = mi.Invoke(null,new []{leftCurrent, rightCurrent});
if(notEqualProps != null)
result.Add(new ArraysDiffResult(i, notEqualProps as List<string>));
Why does this code throws InvalidOperationException ( Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.) ?
NotEqualProperties is static generic method..
UPD : I've already found solution. Just forgot to assign new MethodInfo...(Epic Fail..)
But how about performance?
MakeGenericMethod
returns a new MethodInfo
instance. (MethodInfo
is immutable)
Your code creates this new instance, throws it away, then continues using the open (non-parameterized) MethodInfo
.
You need to use the new instance, like this:
mi = mi.MakeGenericMethod(leftCurrent.GetType());
Yes; reflection is much slower than normal method calls.
However, unless you're calling it in a tight loop, it's not necessarily an issue.
You didn't assign the result of
mi.MakeGenericMethod(leftCurrent.GetType());
to anything. Note that MakeGenericMethod
does not mutate the invoking instance.
P.S Is this code much slower than calling method directly (without mi.Invoke) ?
Much? I don't know. The only way to know is to set performance benchmarks and to profile.
Oh, I'm stupid...It should be :
mi = mi.MakeGenericMethod(leftCurrent.GetType());
(Facepalm...). But how about performance?
精彩评论