【问题标题】:How to get value from a KeyValuePair<> with unknown type如何从类型未知的 KeyValuePair<> 中获取值
【发布时间】:2019-09-26 19:08:33
【问题描述】:

我有一个我不知道其类型的 KeyValuePair 对象。我需要将此 KeyValuePair 的值作为对象。

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

我知道这将涉及使用反射。

【问题讨论】:

  • 那么你是从哪里得到的?
  • dynamic 会帮忙吗?
  • 请阅读How to Ask并创建一个minimal reproducible example
  • 您想知道 KeyValuePair 中“值”的类型吗?
  • @Stefan 不,您不能将 KeyValuePair 转换为 KeyValuePair

标签: c# reflection keyvaluepair


【解决方案1】:

请参阅以下主题。你会在那里找到比你需要的更多的东西:C# Reflection - How can I tell if object o is of type KeyValuePair and then cast it?

乐:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    相关资源
    最近更新 更多