C#使用TypeDescriptor时遭遇Newtonsoft.Json程序集加载异常求助
问题分析
调用System.ComponentModel.TypeDescriptor.GetConverter(type).IsValid(value)时抛出System.IO.FileNotFoundException,原因是遍历的自定义结构体所在类库依赖Newtonsoft.Json 13.0.0.0版本,但当前运行环境找不到该版本的程序集。仅使用内置类型时无异常,说明内置类型的转换器不依赖第三方库,而自定义结构体的类型转换器(或其内部逻辑)需要加载缺失的Newtonsoft.Json版本。
解决方案
以下是几种可行的解决办法:
1. 安装匹配版本的Newtonsoft.Json
直接在当前项目中通过NuGet安装13.0.0.0版本的Newtonsoft.Json:
Install-Package Newtonsoft.Json -Version 13.0.0
或通过.NET CLI执行:
dotnet add package Newtonsoft.Json --version 13.0.0
2. 配置程序集绑定重定向
如果当前项目已使用其他版本的Newtonsoft.Json,不想切换版本,可以在app.config(或web.config)中添加绑定重定向,让运行时用现有版本替代缺失的13.0.0.0版本:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="你的项目当前使用的版本号" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
注意将你的项目当前使用的版本号替换为实际版本(比如12.0.3)。
3. 过滤第三方自定义结构体类型
如果不需要对第三方库的自定义结构体做转换校验,遍历Types集合时直接过滤掉这些类型:
// 只保留.NET内置类型或你自己可控的类型 foreach (Type type in Types.Where(t => t.Assembly == typeof(string).Assembly || t.Assembly == typeof(你的自定义类型).Assembly)) { // 原有校验逻辑 }
4. 捕获异常并跳过问题类型
在获取转换器或调用IsValid时添加异常捕获,遇到程序集加载异常时跳过该类型的校验:
public static bool CanCovertToValue(this string value) { foreach (Type type in Types) { bool isValid = false; try { isValid = System.ComponentModel.TypeDescriptor.GetConverter(type).IsValid(value); } catch (FileNotFoundException) { // 跳过依赖缺失的类型 continue; } catch (FileLoadException) { // 处理版本不匹配的加载异常 continue; } if (isValid) { if (type == typeof(string)) { return value.StartsWith("\"") && value.EndsWith("\""); } else if (type == typeof(Uri)) { return value.StartsWith("\"") && value.EndsWith("\""); } else if (type == typeof(char)) { return value.StartsWith("'") && value.EndsWith("'"); } else { return true; } } } return false; }
内容的提问来源于stack exchange,提问作者Toxic Cookie
相关产品推荐
相关产品推荐

