c# - 反射返回“未定义”的扩展方法
问题描述
我正在运行 .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
物体或其他东西来检测这一点?
解决方案
虽然您的应用程序以框架版本 4.6 为目标,但这意味着这是它可以运行的框架的最低版本。这个目标基本上告诉编译器在您开发和编译程序时哪些“API”可用,但请记住反射没有编译时安全性。它只是按照您在运行时告诉它的操作,并且您希望它有效。
在您的示例中,您正在运行的框架版本(不是目标)是 4.7.2。我知道这一点是因为您通过反射找到了一种仅在 4.7.2 上存在的方法
推荐阅读
- spring-boot - Spring Boot 2.x Hikari 连接默认属性和值
- python - 如何从数据库中超时 Sqlalchemy - 不是从 sqlalchemy 中超时数据库
- laravel - Laravel:在控制器中执行功能
- javascript - 我正在尝试将包含输入文本的 h2 添加到具有类“the-div”的 div
- bash - 使用 Bash 删除数据框中的选项卡
- discord - Selfbot 的 Discord API “软禁令”?它只能读取自己的消息
- c++ - 重新定义类型名称是否合法?
- flutter - 收到 FCM 后自动启动 Flutter 应用
- python - 驱动程序不抓取标签的更新内容并抓取旧内容
- python - 为什么 sqlalchemy 不创建我的其他表