Dot Net Core 不一致

Dot Net Core being Inconsistent

我的应用程序有一个问题,当在程序集 Sigil v4.7 上调用 GetCustomAttributes 时,它抛出异常。

但这只发生在特定情况下。如果通过 Jil v2.15.4 添加 Sigil v4.7,那么它就会发生。

如果直接添加 Sigil v4.7,它不会重现。同样,如果您添加最新版本的 Jil (v2.17.0),它仍然引用 Sigil v4.7,它不会重现。

我很困惑为什么给定相同的 dll,我会得到不同的结果。

这是我的测试代码:

using System.Diagnostics;
using System.Linq;
using System.Reflection;

namespace WindowsAssemblyTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var sigilAssembly = AppDomain.CurrentDomain.GetAssemblies()
                                         .FirstOrDefault(x => x.FullName.Contains("Sigil"));

            try
            {
                var attrs = sigilAssembly?.GetCustomAttributes(typeof(AssemblyProductAttribute), false)
                                          .OfType<AssemblyProductAttribute>();

                Debug.WriteLine(">>>>>>  Success: " + sigilAssembly?.GetName());
            }
            catch (System.IO.FileNotFoundException exception)
            {
                Debug.WriteLine(">>>>>>  Failed: " + sigilAssembly?.GetName() + " with " + exception.Message);
            }

            // This is here so the compiler does not remove the reference to Sigil.
            var createReferenceToSigil = Sigil.OptimizationOptions.All;    
        }
    }
}

要重现此问题,请创建一个 .net 核心控制台应用程序并将以上代码添加到 program.cs。然后添加对 Jil v2.15.4 和 运行 的 NuGet 引用。调试 window 将显示:

>>>>>> Failed: Sigil, Version=4.7.0.0, Culture=neutral, PublicKeyToken=2d06c3494341c8ab with Could not load file or assembly 'System.Runtime.InteropServices.PInvoke, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

如果您随后升级到 Jil v2.17.0,您将看到:

>>>>>> Success: Sigil, Version=4.7.0.0, Culture=neutral, PublicKeyToken=2d06c3494341c8ab

为什么同一个版本的 dll Sigil 对于 Jil 的一个版本会失败,而对于另一个版本则不会?

我认为这个问题与 Sigil 无关。正如您在评论中提到的,它发现 Sigil 很好,但在 GetCustomAttributes.

上失败了

这就是问题所在:GetCustomAttributes 依赖于 System.Runtime.InteropServices.PInvoke

那为什么你用的是Jil v2.17.0却找不到v2.15.4呢PInvoke

查看两者的依赖关系Jil v2.17.0 and Jil v2.15.4。区别在于2.17.0支持.NETStandard 2.0,而v2.15.4只支持.NETStandard 1.6

很难找到确切的问题所在,但如果您搜索 "System.Runtime.InteropServices.PInvoke" "GetCustomAttributes" you will find several results that explain that System.Runtime.InteropServices.PInvoke was not available in .NET Core 1.0. (it was in the release candidate, but removed before release)

所以我相信发生的事情是,如果您使用较新的包,它在 .NETStandard 2.0 下 运行 并且 PInvoke 可用。