C# C Nullable:如何从Dictionary

C# C Nullable:如何从Dictionary,c#,nullable,C#,Nullable,我有一个参数字典,想创建一个FormUrlEncodedContent。请参见以下示例代码: var message=newdictionary{{example,example}}; var content=新FormUrlEncodedContentmessage; 这段代码在禁用nullable的情况下运行良好,但启用它会导致警告,因为我们启用了WarningAsErrors,所以构建失败 Argument of type 'System.Collections.Generic.Dicti

我有一个参数字典,想创建一个FormUrlEncodedContent。请参见以下示例代码:

var message=newdictionary{{example,example}}; var content=新FormUrlEncodedContentmessage; 这段代码在禁用nullable的情况下运行良好,但启用它会导致警告,因为我们启用了WarningAsErrors,所以构建失败

Argument of type 'System.Collections.Generic.Dictionary<string,string>' cannot
be used for parameter 'nameValueCollection' of type 
'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string?,string?>>'
in 'System.Net.Http.FormUrlEncodedContent.FormUrlEncodedContent'
due to differences in the nullability of reference types.
我通过执行message.Selectkvp=>newkeyvaluepairkvp.Key、kvp.Value解决了这个问题,但这非常冗长、粗糙,而且可能更慢


有什么建议吗?我是否缺少一种明显的方式来强制转换此内容,或者FormUrlEncodedContent类接受KeyValuePair是错误的?

我似乎找到了一种方法,可以使用as来解决此问题:

var content=new FormUrlEncodedContent message.aseneumerable作为IEnumerable;
我似乎找到了一种解决方法,使用as:

var content=new FormUrlEncodedContent message.aseneumerable作为IEnumerable; 关键在于:

var message=newdictionary{{example,example}}; var content=newformurlencodedcontentmessage!; 关键在于:

var message=newdictionary{{example,example}}; var content=newformurlencodedcontentmessage!;
我所知道的当前C的最佳解决方案是使用!:

可空启用 使用System.Collections.Generic; 使用System.Net.Http; var message=newdictionary{{example,example}}; var content=newformurlencodedcontentmessage!; 这里的问题是,结构和类类型参数是相同的。因此,我们不允许隐式地将KeyValuePair转换为KeyValuePair,例如,即使这样做没有真正的安全问题

一个类似问题的解决方案已经完成。也许该语言应该引入一个在Task和KeyValuePair场景中都能工作的解决方案,也许还可以扩展到其他场景


编辑:这个问题还揭示了编译器中的一个错误,某些不允许的嵌套可空性转换不会产生警告。为了避免依赖这个bug,我更改了推荐的解决方案

我所知道的当前C的最佳解决方案是使用!:

可空启用 使用System.Collections.Generic; 使用System.Net.Http; var message=newdictionary{{example,example}}; var content=newformurlencodedcontentmessage!; 这里的问题是,结构和类类型参数是相同的。因此,我们不允许隐式地将KeyValuePair转换为KeyValuePair,例如,即使这样做没有真正的安全问题

一个类似问题的解决方案已经完成。也许该语言应该引入一个在Task和KeyValuePair场景中都能工作的解决方案,也许还可以扩展到其他场景


编辑:这个问题还揭示了编译器中的一个错误,某些不允许的嵌套可空性转换不会产生警告。为了避免依赖这个bug,我更改了推荐的解决方案

谢谢,这正是我想要的!谢谢,这正是我想要的!