[英]C# Delegate vs Reflection
I'm trying to optimize a method and can't get to the solution.. 我正在尝试优化方法,却无法解决问题。
I have the following class: 我有以下课程:
public class X : MyInterface<Model>
{
public void Execute(Model m) { }
}
I am trying to invoke Execute(...) I know the Type of X and I know the Type of Model. 我正在尝试调用Execute(...),我知道X的类型,并且我知道模型的类型。
This works: 这有效:
(here logic to find the correct method).Method.Invoke(InstanceX, new object[] { m });
This does not but should work faster: 这不会,但是应该可以更快地工作:
(here logic to find the correct method).Method.CreateDelegate(Expression.GetDelegateType(typeof(m)), instanceX);
Error: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type. 错误:无法绑定到目标方法,因为其签名或安全性透明性与委托类型的签名或安全性透明性不兼容。
Again; 再次; trying to optimize, so any other solution that works faster than the reflection Invoke would be cool.
尝试进行优化,因此任何比反射调用更快的解决方案都很棒。
Solution without reflection (to create delegate): 没有反思的解决方案(创建委托):
// assuming existence of class BaseModel and class XModel : BaseModel
public interface IBaseClass {
void Execute(BaseModel model);
}
public abstract class BaseClass<TModel> : IBaseClass where TModel : BaseModel {
public void Execute(BaseModel model) {
this.Execute((TModel)model);
}
protected abstract void Execute(TModel model);
}
public class X : BaseClass<XModel> {
protected override Execute(XModel model) {
...
}
}
Sample usage: 用法示例:
var typeX = typeof(X);
var typeXModel = typeof(XModel);
var x = (IBaseClass)Activator.CreateInstance(typeX);
x.Execute((BaseModel)Activator.CreateInstance(typeXModel));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.