简体   繁体   English

C#构造通用方法

[英]C# constructing generic method

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.) ? 为什么此代码会引发InvalidOperationException(无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作。)?

NotEqualProperties is static generic method.. NotEqualProperties是静态的泛型方法。

UPD : I've already found solution. UPD:我已经找到解决方案。 Just forgot to assign new MethodInfo...(Epic Fail..) 只是忘记分配新的MethodInfo ...(Epic Fail ..)

But how about performance? 但是性能如何?

MakeGenericMethod returns a new MethodInfo instance. MakeGenericMethod返回一个新的MethodInfo实例。 ( MethodInfo is immutable) MethodInfo是不可变的)

Your code creates this new instance, throws it away, then continues using the open (non-parameterized) MethodInfo . 您的代码创建了这个新实例,将其丢弃,然后继续使用打开的(非参数化) 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. 请注意, MakeGenericMethod不会使调用实例发生变异。

PS Is this code much slower than calling method directly (without mi.Invoke) ? PS此代码是否比直接调用方法(没有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...). (Facepalm ...)。 But how about performance? 但是性能如何?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM