c# - .Net Standard 2.0 dll 的 .Net 45 序列化

标签 c# .net .net-standard jsonserializer .net-standard-2.0

我有一个 .Net 标准 2.0 应用程序,它引用了 .Net45 dll 中的一些契约(Contract)。我这样做的印象是,一旦这些契约(Contract)对象被序列化,它们将使用 .Net45 程序集类型来完成。使用 .Net45 库(这是最终目标)反序列化这些现在给出错误:

Error resolving type specified in JSON 'System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib],[System.String, System.Private.CoreLib]], System.Private.CoreLib'

这显然是因为它试图从标准程序集类型而不是 mscorlib 中解析字符串类型。有什么办法可以实现我正在尝试的目标吗?

最佳答案

有许多不同的方法可以解决这个问题。

对于无法轻松转换为自定义 ISerializationBinder 的大型代码库 我已经实现了一个重定向(不是很漂亮,但它有效)

RedirectAssembly("System.Private.CoreLib", "mscorlib");

public static void RedirectAssembly(string fromAssemblyShotName, string replacmentAssemblyShortName)
{
    Console.WriteLine($"Adding custom resolver redirect rule form:{fromAssemblyShotName}, to:{replacmentAssemblyShortName}");
    ResolveEventHandler handler = null;
    handler = (sender, args) =>
    {
        // Use latest strong name & version when trying to load SDK assemblies
        var requestedAssembly = new AssemblyName(args.Name);
        Console.WriteLine($"RedirectAssembly >  requesting:{requestedAssembly}; replacment from:{fromAssemblyShotName}, to:{replacmentAssemblyShortName}");
        if (requestedAssembly.Name == fromAssemblyShotName)
        {
            try
            {
                Console.WriteLine($"Redirecting Assembly {fromAssemblyShotName} to: {replacmentAssemblyShortName}");
                var replacmentAssembly = Assembly.Load(replacmentAssemblyShortName);
                return replacmentAssembly;
            }
            catch (Exception e)
            {
                Console.WriteLine($"ERROR while trying to provide replacement Assembly {fromAssemblyShotName} to: {replacmentAssemblyShortName}");
                Console.WriteLine(e);
                return null;
            }
        }

        Console.WriteLine($"Framework faild to find {requestedAssembly}, trying to provide replacment from:{fromAssemblyShotName}, to:{replacmentAssemblyShortName}");

        return null;
    };

    AppDomain.CurrentDomain.AssemblyResolve += handler;
}

关于c# - .Net Standard 2.0 dll 的 .Net 45 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45961442/

相关文章:

.net - .NET 3.5 的 SP1 中的新增功能

c# - 发出一个类覆盖两个具有相同名称的接口(interface)方法

c# - 如何将文件打印到特定打印机

c# - 使用异步和等待在 MVC 中返回 RedirectToAction

c# - 由多个线程读取/写入的字段,Interlocked 与 volatile

c# - '无法加载文件或程序集 'netstandard, Version=2.0.0.0, ...'。不应加载引用程序集以执行

c# - NuGet 包应支持哪些 .NET 版本以最大限度地提高其可用性和功能?

localization - 带有新 csproj 的 .NET Standard (1.4) 中的资源文件

c# - 在路径中使用 "~"解析为 C :\

javascript - C# WPF 应用程序 webbrowser 无法运行 angularjs