简体   繁体   中英

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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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