我经常听到反射的糟糕程度.虽然我一般都避免反思,很少发现没有它就无法解决问题的情况,我想知道......
对于那些在应用程序中使用过反射的人,你是否测量过性能命中率,是否真的如此糟糕?
有很多关于加速反射调用的帖子,例如:
https://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates/
和这里:
示例:使用.NET/C#中的委托加速Reflection API
我的问题是关于加速泛型调用.这有可能吗?
我有一个抽象类和一个实现它的类......
public abstract class EncasulatedMessageHandler<T> where T : Message
{
public abstract void HandleMessage(T message);
}
public class Handler : EncasulatedMessageHandler<MyMessageType>
{
public int blat = 0;
public override void HandleMessage(MyMessageType message) { blat++; }
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是建立这些消息处理程序类的列表并快速调用它们的HandleMessage()
目前,我正在做的事情大致如下:
object handler = Activator.CreateInstance(typeof(Handler)); // Ignore this, this is done up front.
MethodInfo method = type.GetMethod("HandleMessage", BindingFlags.Instance | BindingFlags.Public);
Action<object> hook = new Action<object>(delegate(object message)
{
method.Invoke(handler, new object[] { message });
});
// …Run Code Online (Sandbox Code Playgroud) 由于被要求在这个岗位,我想出了一个使用委派用来加快在.NET/C#恢复体力的例子.
但是,运行时出现此错误(编译工作正常).可能有什么问题?
Unhandled Exception: System.ArgumentException: type is not a subclass of Multicastdelegate
at System.Delegate.CreateDelegate (System.Type type, System.Object firstArgument, System.Reflection.MethodInfo method, Boolean throwOnBindFailure, Boolean allowClosed) [0x00000] in <filename unknown>:0
at System.Delegate.CreateDelegate (System.Type type, System.Reflection.MethodInfo method, Boolean throwOnBindFailure) [0x00000] in <filename unknown>:0
at System.Delegate.CreateDelegate (System.Type type, System.Reflection.MethodInfo method) [0x00000] in <filename unknown>:0
at EX.RefTest.DelegateTest () [0x00000] in <filename unknown>:0
at EX.RefTest.Main () [0x00000] in <filename unknown>:0
Run Code Online (Sandbox Code Playgroud)
这是(工作)源代码,感谢Jon&ChaosPandion的帮助.
using System.Reflection;
using System;
namespace EX
{
public class Hello
{
// …Run Code Online (Sandbox Code Playgroud)