gpt4 book ai didi

c# - NET Native Tool Chain for UWP 在可移植库中抛出 NotImplementedException

转载 作者:行者123 更新时间:2023-11-30 23:12:38 25 4
gpt4 key购买 nike

我们有一个相当大的共享项目,可以说有 3 个负责人:

  • Windows.UWP
  • Windows.Desktop81
  • Windows.Phone81

这三个都引用了同时针对 Windows 8.1 和 Windows Phone 8.1 的可移植库。

使用 native 工具链编译 UWP 项目时,可移植库无法访问任何类型信息,因此它们无法执行任何反射。

失败的方法是一个通用方法,检查 typeof(T) 以根据它的类型执行各种操作。

抛出 System.NotImplementedException 的第一行是:

If (typeof(T).IsArray)

在这种情况下,T 是 System.String,如果我在失败的方法上中断调试器并在 visual studio 2015 的即时窗口中键入,我得到:

>> typeof(string).IsArray
An internal error has occurred while evaluating method System.Type.get_IsArray().

但是,如果我在 App.OnLaunched 方法中执行相同的操作,则效果很好。因此可移植库无法访问任何类型信息,即使是 System.String 等系统类型也是如此。

我已经尝试为可移植库添加平台指令,但到目前为止还没有成功。

关于如何启用可移植库以访问类型信息,您是否有任何信息。

最佳答案

我通过电子邮件收到了 Microsoft 的 Michal 的回复,解释了根本原因以及如何解决它。

You seem to be hitting the same issue described here: https://github.com/dotnet/corert/issues/3565, except the method in question is Type.IsArray instead of ConstructorInfo.Invoke.

The problem is that the method Type.IsArray is declared as non-virtual in the Portable Library contracts that your source code compiles against, but it is virtual in the implementation assemblies used in .NET Native. This is normally not a big problem because the C# compiler pretty much always uses “callvirt” instruction to call the method (even if it’s not virtual). The C# compiler shipped in Visual Studio 2017 started doing an optimization that if a method is not virtual and the 'this' passed to the method is known not to be null, it uses “call” instead of “callvirt”. The result is that the code ends up calling a method that should never have been called. The result of the typeof() expression is known to be never null.

The good news is that we made IsArray non-virtual again as part of the NetStandard 2.0 effort. The bad news is that .NET Native with support for NetStandard 2.0 hasn’t shipped yet.

You’ll need a workaround. The easiest I can think of is to add an extension method and use that instead:

static class NetNativeWorkarounds
{
public static bool IsArray(this Type type) => type.IsArray;
}

Using the extension method avoids the C# compiler optimization because this condition is not met (the compiler doesn’t know what type you’ll pass to the extension method and has to do a callvirt to the Type.IsArray method).

关于c# - NET Native Tool Chain for UWP 在可移植库中抛出 NotImplementedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43999144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com