首页 > 解决方案 > C# - 我如何转换 KeyValuePair到键值对?

问题描述

在 C# 中,如何将KeyValuePair<string, object>转换为KeyValuePair<object, object>?我尝试了以下方法,但它不起作用:

public static KeyValuePair<object, object> DoTheCast(KeyValuePair<string, object> the_obj)
{
    return (KeyValuePair<object, object>)the_obj;
}

InvalidCastException:无法将“System.Collections.Generic.KeyValuePair[System.String,System.Object]”类型的对象转换为“System.Collections.Generic.KeyValuePair[System.Object,System.Object]”类型。

标签: c#castingkey-value

解决方案


您将无法施放pers,但您可以创建一个新的

public static KeyValuePair<object, object> DoTheCast(KeyValuePair<string, object> the_obj)    
     => new KeyValuePair<object, object>(the_obj.Key, the_obj.Value);

推荐阅读