简体   繁体   English

如何在不使用反射的情况下确定对象是否为KeyValue <,>对的某种类型

[英]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. 我需要确定一个对象是否具有某种类型的KeyValue对。 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 / Catch块之类的东西?

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

    }
}

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

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