Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

generics - C# Reflection - How can I tell if object o is of type KeyValuePair and then cast it?

I'm currently trying to write a Dump() method from LinqPad equivalent iin C# for my own amusment. I'm moving from Java to C# and this is an exercise rather than a business requirement. I've got almost everything working except for Dumping a Dictionary.

The problem is that KeyValuePair is a Value type. For most other Value types I simply call the ToString method but this is insufficient as the KeyValuePair may contain Enumerables and other objects with undesirable ToString methods. So I need to work out if it's a KeyValuePair and then cast it. In Java I could use wildcard generics for this but I don't know the equivalent in C#.

Your quest, given an object o, determine if it's a KeyValuePair and call Print on its key and value.

Print(object o) {
   ...
}

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...