Retrieve Key and Value from System.Object as KeyValuePair in C#
To retrieve the Key and Value from a System.Object that is actually an instance of KeyValuePair in runtime, you can use the following steps:\n\n1. Cast the System.Object to KeyValuePair.\n2. Access the Key and Value properties of the KeyValuePair instance.\n\nHere's an example code snippet to demonstrate this:\n\ncsharp\nSystem.Object item = GetMyObject();\n\n// Check if the item is KeyValuePair\nif (item is KeyValuePair<string, int>) \n{\n    // Cast the item to KeyValuePair\n    KeyValuePair<string, int> keyValue = (KeyValuePair<string, int>)item;\n\n    // Retrieve the Key and Value\n    string key = keyValue.Key;\n    int value = keyValue.Value;\n\n    // Print the Key and Value\n    WriteLine($"{key}, {value}");\n}\nelse\n{\n    // Handle the case when the item is not KeyValuePair\n    WriteLine("Invalid object type");\n}\n\n\nMake sure to replace string and int in the cast and KeyValuePair<string, int> with the actual types of Key and Value in your case.
原文地址: https://www.cveoy.top/t/topic/qaLd 著作权归作者所有。请勿转载和采集!