在.NET Core中使用Reflection
对于跨平台开发,我正在尝试创建.NET Core共享库。 我在VS 2015中使用了Class Library (package)
项目模板。我的库需要在完整的.net 4框架中使用我熟悉的一些reflection机制,但我现在不知道如何在.NET Core中访问它们图书馆。 特别:
-
Delegate
类型具有Method
属性,该属性返回MethodInfo
对象。 -
Type
类有一个BaseType
属性,FilterName
属性,InvokeMember
方法和我在.NET Core中无法访问的FindMembers
方法。
我添加了NuGet包,据称有我需要的reflection件:
"frameworks": { "net451": { "dependencies": { "System.Reflection": "4.1.0-beta-23516", "System.Reflection.Extensions": "4.0.1-beta-23516", "System.Reflection.Primitives": "4.0.1-beta-23516", } }, "dotnet5.4": { "dependencies": { "Microsoft.CSharp": "4.0.1-beta-23516", "System.Collections": "4.0.11-beta-23516", "System.Linq": "4.0.1-beta-23516", "System.Reflection": "4.1.0-beta-23516", "System.Reflection.Extensions": "4.0.1-beta-23516", "System.Reflection.Primitives": "4.0.1-beta-23516", "System.Runtime": "4.0.21-beta-23516", "System.Threading": "4.0.11-beta-23516" } } }, "dependencies": { "System.Reflection.TypeExtensions": "4.1.0-beta-23516" }
我还添加了using System.Reflection
,但我仍然收到错误,表明这些属性和类型未定义。
我究竟做错了什么?
如果它是相关的,在同一台机器上命令dnvm list
显示:
Active Version Runtime Architecture OperatingSystem Alias ------ ------- ------- ------------ --------------- ----- 1.0.0-rc1-update1 clr x64 win 1.0.0-rc1-update1 clr x86 win 1.0.0-rc1-update1 coreclr x64 win * 1.0.0-rc1-update1 coreclr x86 win default
以上就是我想要的……或者至少我认为我想要的东西。 ;)
简答
我究竟做错了什么?
您正在尝试访问.NET 4.5.1中可用但不在5.4中的成员。
4.x Workaround in 5.x/Core Delegate.Method. Delegate.GetMethodInfo() Type.BaseType. Type.GetTypeInfo() Type.FilterName - Type.InvokeMember - Type.FindMembers -
直接从Visual Studio剪切。
如果我们将鼠标hover在错误上,Visual Studio会告诉我们。
.NET可移植性报告
还值得一看.NET可移植性分析器 。 它是我们可以从Visual Studio库安装的扩展。
例如,运行它告诉我们Type.BaseType
不可用并建议一种解决方法。
如果您不希望原始代码充满#if ... #else ... #endif
语句,您可以使用https://www.nuget.org/packages/ReflectionBridge/等帮助程序库,它提供了一些扩展名它定义了Type和TypeInfo之间差异的桥梁。
(源代码https://github.com/StefH/ReflectionBridge )
我正在使用.net Core 1.0。 尝试下面的project.json片段,看看是否适合你。 我还注意到您正在使用beta API,因此如果可能的话,请继续使用beta版。
{ "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "dependencies": { "NETStandard.Library": "1.0.0-rc2-23811", "System.Reflection.TypeExtensions": "4.0.0" }, "frameworks": { "dnxcore50": { } } }