栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用反射调用扩展方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用反射调用扩展方法?

就像其他人所说的那样,扩展方法是编译器的魔力,您可以始终使用VS右键单击,转到定义以查找实现静态方法的真实类型。

从那里开始,它变得很 毛茸茸

Where
重载,因此您需要找到与所需签名匹配的实际定义。
GetMethod
泛型类型有一些限制,因此您必须使用搜索找到实际的类型。

找到方法后,必须

MethodInfo
使用该
MakeGenericMethod
调用进行特定设置。

这是一个完整的工作示例:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Reflection;namespace ConsoleApplication9 {    class Program {        class MyObject { public string Name { get; set; }        }        public static void CallWhereMethod() { List<MyObject> myObjects = new List<MyObject>() {      new MyObject { Name = "Jon Simpson" },     new MyObject { Name = "Jeff Atwood" } }; Func<MyObject, bool> NameEquals = BuildEqFuncFor<MyObject>("Name", "Jon Simpson"); // The Where method lives on the Enumerable type in System.Linq var whereMethods = typeof(System.Linq.Enumerable)     .GetMethods(BindingFlags.Static | BindingFlags.Public)     .Where(mi => mi.Name == "Where"); Console.WriteLine(whereMethods.Count()); // 2 (There are 2 methods that are called Where) MethodInfo whereMethod = null; foreach (var methodInfo in whereMethods) {     var paramType = methodInfo.GetParameters()[1].ParameterType;     if (paramType.GetGenericArguments().Count() == 2) {         // we are looking for  Func<TSource, bool>, the other has 3         whereMethod = methodInfo;     } } // we need to specialize it  whereMethod = whereMethod.MakeGenericMethod(typeof(MyObject)); var ret = whereMethod.Invoke(myObjects, new object[] { myObjects, NameEquals }) as IEnumerable<MyObject>; foreach (var item in ret) {     Console.WriteLine(item.Name); } // outputs "Jon Simpson"        }        public static Func<T, bool> BuildEqFuncFor<T>(string prop, object val) { return t => t.GetType().InvokeMember(prop, BindingFlags.GetProperty,     null, t, null) == val;        }        static void Main(string[] args) { CallWhereMethod(); Console.ReadKey();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465357.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号