If you don't know the types stored in the KeyValuePair
you need to exercise a bit of reflection code.
Let's look at what is needed:
First, let's ensure the value isn't null
:
if (value != null)
{
Then, let's ensure the value is generic:
Type valueType = value.GetType();
if (valueType.IsGenericType)
{
Then, extract the generic type definition, which is KeyValuePair<,>
:
Type baseType = valueType.GetGenericTypeDefinition();
if (baseType == typeof(KeyValuePair<,>))
{
Then extract the types of the values in it:
Type[] argTypes = baseType.GetGenericArguments();
Final code:
if (value != null)
{
Type valueType = value.GetType();
if (valueType.IsGenericType)
{
Type baseType = valueType.GetGenericTypeDefinition();
if (baseType == typeof(KeyValuePair<,>))
{
Type[] argTypes = baseType.GetGenericArguments();
// now process the values
}
}
}
If you've discovered that the object does indeed contain a KeyValuePair<TKey,TValue>
you can extract the actual key and value like this:
object kvpKey = valueType.GetProperty("Key").GetValue(value, null);
object kvpValue = valueType.GetProperty("Value").GetValue(value, null);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…