C# NET中有封装MethodInfo+实例的抽象吗?
我正在玩反射,我想封装对实例方法的调用 我总是做这样的事情:C# NET中有封装MethodInfo+实例的抽象吗?,c#,.net,reflection,C#,.net,Reflection,我正在玩反射,我想封装对实例方法的调用 我总是做这样的事情: methodInfo.Invoke(instance, parameters) 我想知道是否有任何方法可以将其封装为call.Invokeparameters之类的东西,其中实例是隐式的。为什么不简单地这样做: public class MethodInvoker { private MethodInfo _method; private object _target; public MethodInvok
methodInfo.Invoke(instance, parameters)
我想知道是否有任何方法可以将其封装为call.Invokeparameters之类的东西,其中实例是隐式的。为什么不简单地这样做:
public class MethodInvoker
{
private MethodInfo _method;
private object _target;
public MethodInvoker(MethodInfo method, object target)
{
_method = method;
_target = target;
}
public object Invoke(params object[] parameters) => _method.Invoke(_target, parameters);
}
...
string s = "Hello";
var invoker = new MethodInvoker(s.GetType().GetMethod("Substring",new Type[] { typeof(int), typeof(int) }), s);
Console.WriteLine(invoker.Invoke(1,3));
您可以在目标或返回类型上使用泛型来实现类型安全。您可以创建绑定实例的委托。 可以使用static Delegate.CreateInstance方法或MethodInfo.CreateInstance方法执行此操作。前者依赖于您知道该实例实际上是该方法的第一个隐藏参数,因此后者可能更清楚一些 阶级事务 { 整数; 公共Thingint编号{u number=number;} public int GetNumber{return_Number;} } 公共静态真空总管 { 新事物=新事物1; 事物2=新事物2; MethodInfo getter=typeofThing.GetMethodGetNumber; Func getOne=FuncDelegate.CreateDelegatetypeofFunc,thingOne,getter; Func getTwo=Funcgetter.CreateDelegatetypeofFunc,thingTwo; Console.WriteLinegTone; Console.WriteLinegetTwo; }
您是在系统库中查找某些内容,还是只想为自己编写一些内容?