简体   繁体   English

如何从类型未知的 KeyValuePair<> 中获取值

[英]How to get value from a KeyValuePair<> with unknown type

I have an object that is a KeyValuePair<> whose types I do not know.我有一个 object,它是一个我不知道其类型的 KeyValuePair<>。 I need to get the Value of this KeyValuePair as object.我需要将此 KeyValuePair 的值作为 object。

object kvpair = ... ;         // This is a KeyValuePair<K, V> with unknown K and V.
object value = kvpair.Value;  // I want to get the value of the kvpair

I understand this will involve using reflection.我知道这将涉及使用反射。

Please see the following topic.请参阅以下主题。 You will find more than you need there: C# Reflection - How can I tell if object o is of type KeyValuePair and then cast it?你会在那里找到比你需要的更多: C# 反射 - 我如何判断 object o 是否属于 KeyValuePair 类型,然后进行转换?

LE:乐:

KeyValuePair<string, string> kvp = new KeyValuePair<string, string>("key", "value");
Type aux = kvp.GetType();
object kvpValue = aux.GetProperty("Value").GetValue(kvp, null);
Console.WriteLine(kvpValue);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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