"aren't defined" 的反射返回扩展方法
Reflection returning extension methods that "aren't defined"
我是 运行 .net 4.6 应用程序。
我正在使用反射来查找扩展方法ToHashSet
此方法was introduced in .net 4.7.2,"does not"存在于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 为目标,但这意味着它可以 运行 对抗框架的最低版本。这个目标本质上告诉编译器什么 'APIs' 在你开发和编译你的程序时可用,但记住反射没有编译时安全性。它只是按照你在 运行 时告诉它的那样做,你希望它能起作用。
在您的示例中,您运行正在使用(未定位)的框架版本是 4.7.2。我知道这一点是因为您通过反射找到了一种仅存在于 4.7.2
上的方法
我是 运行 .net 4.6 应用程序。
我正在使用反射来查找扩展方法ToHashSet
此方法was introduced in .net 4.7.2,"does not"存在于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 为目标,但这意味着它可以 运行 对抗框架的最低版本。这个目标本质上告诉编译器什么 'APIs' 在你开发和编译你的程序时可用,但记住反射没有编译时安全性。它只是按照你在 运行 时告诉它的那样做,你希望它能起作用。
在您的示例中,您运行正在使用(未定位)的框架版本是 4.7.2。我知道这一点是因为您通过反射找到了一种仅存在于 4.7.2
上的方法