简体   繁体   中英

C# - How can I cast KeyValuePair<string,object> to KeyValuePair<object,object>?

In C#, how can I cast KeyValuePair<string, object> to KeyValuePair<object, object> ? I tried the following but it does not work:

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

InvalidCastException: Unable to cast object of type 'System.Collections.Generic.KeyValuePair[System.String,System.Object]' to type 'System.Collections.Generic.KeyValuePair[System.Object,System.Object]'.

You wont be able to cast perse, however you can just create a new one

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM