//方式一:使用 InvokeMember关键字,性能一般 /// <summary> /// 验证数据字典是否有效 /// </summary> /// <typeparam name="T">操作类</typeparam> /// <typeparam name="S">查找类</typeparam> /// <typeparam name="R">结果类</typeparam> /// <param name="pObj"></param> /// <returns></returns> public virtual bool ValidDict<T, S, R>(string pFuncName, S pObj) { T instance = Activator.CreateInstance<T>(); object[] mParam = new object[] { pObj }; IList<R> mResult = (IList<R>)instance.GetType().InvokeMember(String.IsNullOrEmpty(pFuncName) ? "SelectByFields" : pFuncName,System.Reflection.BindingFlags.InvokeMethod, null, instance, mParam); return mResult.Count > 0; } //Linq 结合 Delegate from method in typeof( Classy ).GetMethods( BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic ) let delegateType = typeof(classyDelegate<,>) select Delegate.CreateDelegate( delegateType, yourInstance, method) 来源:http://stackoverflow.com/questions/2714989/delegate-createdelegate-and-generics-error-binding-to-target-method //=================================================== //方式二:使用 Delegate.CreateDelegate关键字,性能很好 public IList<Campaign> GetSimbaCampaigns(string nick) { //TODO: 动态调用方法 } //调用方法如下: MethodInfo mi = this.GetType().GetMethod(methodName); //.MakeGenericMethod(typeof(MyClass)); methodName=“GetSimbaCampaigns” var del = Delegate.CreateDelegate(typeof(Func<string, IList<Campaign>>), this, mi); var obj = (IList<Campaign>)del.DynamicInvoke(objs); //=================================================== //方式三:使用 dynamic关键字,性能较好 dynamic dync = new TopTaobaoHelper(); dync.GetSimbaCampaigns(objs);
转载于:https://www.cnblogs.com/xust/articles/2612051.html