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

反思以识别扩展方法

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

反思以识别扩展方法

您必须查看所有可能定义扩展方法的程序集。

查找装饰

ExtensionAttribute
有的类,然后查找该类中
装饰有的方法
ExtensionAttribute
。然后检查第一个参数的类型,以查看它是否与您感兴趣的类型匹配。

这是一些完整的代码。可能更严格(它不是检查类型是否嵌套,或者没有至少一个参数),但它应该给您帮助。

using System;using System.Runtime.CompilerServices;using System.Reflection;using System.Linq;using System.Collections.Generic;public static class FirstExtensions{    public static void Foo(this string x) {}    public static void Bar(string x) {} // Not an ext. method    public static void Baz(this int x) {} // Not on string}public static class SecondExtensions{    public static void Quux(this string x) {}}public class Test{    static void Main()    {        Assembly thisAssembly = typeof(Test).Assembly;        foreach (MethodInfo method in GetExtensionMethods(thisAssembly, typeof(string)))        { Console.WriteLine(method);        }    }    static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly,        Type extendedType)    {        var query = from type in assembly.GetTypes()         where type.IsSealed && !type.IsGenericType && !type.IsNested         from method in type.GetMethods(BindingFlags.Static  | BindingFlags.Public | BindingFlags.NonPublic)         where method.IsDefined(typeof(ExtensionAttribute), false)         where method.GetParameters()[0].ParameterType == extendedType         select method;        return query;    }}


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

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

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