简体   繁体   中英

How to determine if an object is some type of KeyValue<,> pair without using reflection

I need to determine if an object is of some type of KeyValue pair. It is not important for me to know which types are used for the key or the value. So: `

public bool IsKeyValuePair (object o)
{
    //What code should go here?
}

This answer describes how to determine this using reflection, however in my case I am processing 100s of thousands of objects and it is creating a bottleneck in my app.

Perhaps there is a way to do it with a Try / Catch block or something?

Try this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Original Objects from your source code
            var myKeyValuePair = new KeyValuePair<string, string>("HELLO", "THERE");
            var notKeyValuePar = "HELLO THERE";

            // This is so we don't know what it is.
            object o1 = myKeyValuePair;
            object o2 = notKeyValuePar;

            // TEST with a KeyValuePair
            if (IsKeyValuePair(o1))
                Console.WriteLine("o1 is KeyValuePair");
            else
                Console.WriteLine("o1 is NOT KeyValuePair");

            // TEST with a string
            if (IsKeyValuePair(o2))
                Console.WriteLine("o2 is KeyValuePair");
            else
                Console.WriteLine("o2 is NOT KeyValuePair");

            Console.ReadLine();
        }

        static private bool IsKeyValuePair(Object o)
        {
            return String.Compare(o.GetType().Name.ToString(), "KeyValuePair`2") == 0;
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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