![](/img/trans.png)
[英]C# - How can I cast KeyValuePair<string,object> to KeyValuePair<object,object>?
[英]C# Reflection - How can I tell if object o is of type KeyValuePair and then cast it?
我目前正在尝试从LinqPad等效的iin C#编写Dump()方法来实现自己的娱乐。 我正在从Java迁移到C#,这是一项练习,而不是一项业务要求。 除转储字典外,我几乎所有工作正常。
问题在于KeyValuePair是一个值类型。 对于大多数其他Value类型,我仅调用ToString方法,但这是不够的,因为KeyValuePair可能包含Enumerables和其他具有不理想的ToString方法的对象。 因此,我需要弄清楚它是否是KeyValuePair,然后进行转换。 在Java中,我可以为此使用通配符泛型,但我不知道C#中的等效项。
给定对象o,您的任务将确定其是否为KeyValuePair,并对其键和值调用Print。
Print(object o) {
...
}
谢谢!
如果您不知道KeyValuePair
存储的类型,则需要执行一些反射代码。
让我们看一下需要什么:
首先,让我们确保该值不为null
:
if (value != null)
{
然后,确保该值是通用的:
Type valueType = value.GetType();
if (valueType.IsGenericType)
{
然后,提取通用类型定义,即KeyValuePair<,>
:
Type baseType = valueType.GetGenericTypeDefinition();
if (baseType == typeof(KeyValuePair<,>))
{
然后提取其中的值的类型:
Type[] argTypes = baseType.GetGenericArguments();
最终代码:
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
}
}
}
如果发现该对象确实包含KeyValuePair<TKey,TValue>
,则可以提取实际的键和值,如下所示:
object kvpKey = valueType.GetProperty("Key").GetValue(value, null);
object kvpValue = valueType.GetProperty("Value").GetValue(value, null);
假设您使用的是通用KeyValuePair,那么您可能需要测试特定的实例化,例如使用键和值的字符串创建的实例化:
public void Print(object o)
{
if (o == null)
return;
if (o is KeyValuePair<string, string>)
{
KeyValuePair<string, string> pair = (KeyValuePair<string, string>)o;
Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
}
}
如果要测试任何类型的KeyValuePair,则需要使用反射。 你呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.