新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Java中用表達(dá)式數(shù)調(diào)用的實例代碼
小編給大家分享一下Java中用表達(dá)式數(shù)調(diào)用的實例代碼,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
成都創(chuàng)新互聯(lián)公司網(wǎng)站建設(shè)由有經(jīng)驗的網(wǎng)站設(shè)計師、開發(fā)人員和項目經(jīng)理組成的專業(yè)建站團隊,負(fù)責(zé)網(wǎng)站視覺設(shè)計、用戶體驗優(yōu)化、交互設(shè)計和前端開發(fā)等方面的工作,以確保網(wǎng)站外觀精美、網(wǎng)站建設(shè)、網(wǎng)站設(shè)計易于使用并且具有良好的響應(yīng)性。
利用表達(dá)式樹構(gòu)建委托改善反射性能 做了一點小更改正好適合自己用
public static class DynamicMethodBuilder {public static Delegate BuildDynamicDelegate(MethodInfo methodInfo, ConstructorInfo constructorInfo = null) {if (methodInfo == null)throw new ArgumentNullException("methodInfo"); ListparamExpressions = methodInfo.GetParameters().Select((p, i) =>{var name = "param" + (i + 1);return Expression.Parameter(p.ParameterType, name); }).ToList(); MethodCallExpression callExpression;if (methodInfo.IsStatic) {//Call(params....)callExpression = Expression.Call(methodInfo, paramExpressions); }else{if (constructorInfo != null) {//Instance(params).Call(params....)List constructorParamExpressions = constructorInfo.GetParameters().Select((p, i) =>{var name = "constparam" + (i + 1);return Expression.Parameter(p.ParameterType, name); }).ToList(); callExpression = Expression.Call(Expression.New(constructorInfo, constructorParamExpressions), methodInfo, paramExpressions); paramExpressions.InsertRange(0, constructorParamExpressions); }else{ callExpression = Expression.Call(Expression.New(methodInfo.ReflectedType), methodInfo, paramExpressions); } }return Expression.Lambda(callExpression, paramExpressions).Compile(); } }
測試:
public class Baby { private readonly DateTime _birthDay; public Baby(DateTime birthDay) { _birthDay = birthDay; } public Baby() { _birthDay = DateTime.Now; } public string GetBabyInfo(string name, int sex) => $"姓名:{name} , 出生天數(shù):{ DateTime.Now- _birthDay} ,性別 :{(sex == 1 ? "男" : "女")}"; } class Program { static void Main(string[] args) { Type targetType = Assembly.GetExecutingAssembly().GetType("ConsoleApplication1.Baby"); MethodInfo methodInfo = targetType.GetMethod("GetBabyInfo", new[] { typeof(string), typeof(int) }); ConstructorInfo constructor = targetType.GetConstructor(new[] { typeof(DateTime) }); WithConstructor(methodInfo, constructor); WithOutConstructor(methodInfo); Console.ReadKey(); } static void WithConstructor(MethodInfo methodInfo, ConstructorInfo constructor) { var func = (Func)DynamicMethodBuilder.BuildDynamicDelegate(methodInfo, constructor); Console.WriteLine(func(DateTime.Now.AddDays(-100), "糖墩兒", 1)); } static void WithOutConstructor(MethodInfo methodInfo) { var func = (Func )DynamicMethodBuilder.BuildDynamicDelegate(methodInfo); Console.WriteLine(func("糖墩兒", 1)); } }
看完了這篇文章,相信你對Java中用表達(dá)式數(shù)調(diào)用的實例代碼有了一定的了解,想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
當(dāng)前題目:Java中用表達(dá)式數(shù)調(diào)用的實例代碼
文章分享:http://fisionsoft.com.cn/article/giooie.html