开发者

C# constructing generic method [duplicate]

This question already has answers here: How do I use reflection to call a generic method? (8 answers) Closed 2 years ago. 开发者_StackOverflow中文版
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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜