簡體   English   中英

如何在不使用反射的情況下確定對象是否為KeyValue <,>對的某種類型

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

我需要確定一個對象是否具有某種類型的KeyValue對。 對於我來說,知道哪種類型用於鍵或值並不重要。 所以:

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

這個答案描述了如何使用反射來確定這一點,但是在我的情況下,我正在處理數十萬個對象,這正在我的應用程序中造成瓶頸。

也許有一種方法可以使用Try / Catch塊之類的東西?

嘗試這個:

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