C# 构造泛型方法
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>));
为什么此代码会抛出 InvalidOperationException(无法对 ContainsGenericParameters 为 true 的类型或方法执行后期绑定操作。)?
NotEqualProperties 是静态泛型方法。
UPD:我已经找到了解决方案。只是忘记分配新的 MethodInfo...(史诗般的失败...)
但是性能怎么样?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MakeGenericMethod
返回一个新的MethodInfo
实例。 (MethodInfo
是不可变的)您的代码创建这个新实例,将其丢弃,然后继续使用开放的(非参数化)
MethodInfo
。您需要使用新实例,如下所示:
是;反射比普通方法调用慢得多。
但是,除非您在紧密循环中调用它,否则这不一定是问题。
MakeGenericMethod
returns a newMethodInfo
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:
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.
您没有将 的结果分配
给任何东西。请注意,
MakeGenericMethod
不会改变调用实例。很多?我不知道。唯一了解的方法是设置性能基准并进行分析。
You didn't assign the result of
to anything. Note that
MakeGenericMethod
does not mutate the invoking instance.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 :
(Facepalm...).
But how about performance?