.NET Standard 中的 GetMethod 等效项
GetMethod equivalent in .NET Standard
在.NET Framework
中你可以很容易的反映方法。例如:
var methodInfo = typeof(object).GetMethod("MemberwiseClone", bindingFlags);
然而,在 .NET Standard
项目中,编译器抱怨:
error CS1061: 'Type' does not contain a definition for 'GetMethod' and
no extension method 'GetMethod' accepting a first argument of type
'Type' could be found (are you missing a using directive or an
assembly reference?)
问:如何使用.NET Standard
进行等效反射?
对于 .NET Core 1.x 中的几乎 所有 反射,您需要 TypeInfo
而不是 Type
。
System.Reflection
命名空间中有GetTypeInfo
的扩展方法,所以你要:
using System.Reflection; // For GetTypeInfo
...
var methodInfo = typeof(object).GetTypeInfo().GetMethod("MemberwiseClone", bindingFlags);
注意 TypeInfo.GetMethod()
doesn't exist .NET Standard earlier than 1.6, but TypeInfo.DeclaredMethods
从 1.0 开始就已经存在了。
.NET Standard 2.0 将成员重新引入 System.Type
(作为将大部分桌面框架恢复到 .NET Standard 的一部分),因此您在面向 2.0+ 时无需经历这个过程。
在.NET Framework
中你可以很容易的反映方法。例如:
var methodInfo = typeof(object).GetMethod("MemberwiseClone", bindingFlags);
然而,在 .NET Standard
项目中,编译器抱怨:
error CS1061: 'Type' does not contain a definition for 'GetMethod' and no extension method 'GetMethod' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)
问:如何使用.NET Standard
进行等效反射?
对于 .NET Core 1.x 中的几乎 所有 反射,您需要 TypeInfo
而不是 Type
。
System.Reflection
命名空间中有GetTypeInfo
的扩展方法,所以你要:
using System.Reflection; // For GetTypeInfo
...
var methodInfo = typeof(object).GetTypeInfo().GetMethod("MemberwiseClone", bindingFlags);
注意 TypeInfo.GetMethod()
doesn't exist .NET Standard earlier than 1.6, but TypeInfo.DeclaredMethods
从 1.0 开始就已经存在了。
.NET Standard 2.0 将成员重新引入 System.Type
(作为将大部分桌面框架恢复到 .NET Standard 的一部分),因此您在面向 2.0+ 时无需经历这个过程。