C# 代表与反思
我正在尝试优化一种方法,但无法找到解决方案 我有以下课程:C# 代表与反思,c#,reflection,delegates,C#,Reflection,Delegates,我正在尝试优化一种方法,但无法找到解决方案 我有以下课程: public class X : MyInterface<Model> { public void Execute(Model m) { } } 这不会但应该更快地工作: (here logic to find the correct method).Method.CreateDelegate(Expression.GetDelegateType(typeof(m)), instanceX); 错误: 无法绑定到
public class X : MyInterface<Model>
{
public void Execute(Model m) { }
}
这不会但应该更快地工作:
(here logic to find the correct method).Method.CreateDelegate(Expression.GetDelegateType(typeof(m)), instanceX);
错误:
无法绑定到目标方法,因为其签名或安全透明性与委托类型的签名或安全透明性不兼容
再次;尝试优化,以便任何其他比反射调用更快的解决方案都会很酷。无反射的解决方案(创建委托):
无反射的解决方案(创建代理):
为什么需要通过反射调用Execute(…)?我有:-Model instance-typeof(X)-typeof(Model)=>我编写的代码创建了一个X的实例,并以Model的实例作为参数调用Execute。您需要添加typeof(void)来获得一个操作,而不是Func委托。为什么需要调用Execute(…)通过反射?我有:-Model instance-typeof(X)-typeof(Model)=>我编写的代码创建了一个X的实例,并以Model的实例作为参数调用Execute。您需要添加typeof(void)来获得一个操作,而不是Func委托。
(here logic to find the correct method).Method.CreateDelegate(Expression.GetDelegateType(typeof(m)), instanceX);
// 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) {
...
}
}
var typeX = typeof(X);
var typeXModel = typeof(XModel);
var x = (IBaseClass)Activator.CreateInstance(typeX);
x.Execute((BaseModel)Activator.CreateInstance(typeXModel));