首页 > 解决方案 > 反射返回“未定义”的扩展方法

问题描述

我正在运行 .net 4.6 应用程序。

我正在使用反射来查找扩展方法ToHashSet

该方法在 .net 4.7.2 中引入,“不”存在于 4.6

在此处输入图像描述

以下程序成功。它能够找到并反思这种不存在的方法。

using System;
using System.Collections.Generic;
using System.Reflection;

namespace TestAppNS
{
    class Program
    {
        static void Main(string[] args) {
            var toHashSet = GetExtensionMethods(typeof(Enumerable)).First(x => x.Name == "ToHashSet");
        }

        private static IEnumerable<MethodInfo> GetExtensionMethods(Type type) {
            return
                from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                where method.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false)
                select method;
        }
    }
}

为什么会这样?

有没有办法通过查看MethodInfo物体或其他东西来检测这一点?

标签: c#visual-studio-2017.net-4.6

解决方案


虽然您的应用程序以框架版本 4.6 为目标,但这意味着这是它可以运行的框架的最低版本。这个目标基本上告诉编译器在您开发和编译程序时哪些“API”可用,但请记住反射没有编译时安全性。它只是按照您在运行时告诉它的操作,并且您希望它有效。

在您的示例中,您正在运行的框架版本(不是目标)是 4.7.2。我知道这一点是因为您通过反射找到了一种仅在 4.7.2 上存在的方法


推荐阅读