如何确定对象是否是某种类型的KeyValue<>;在不使用反射的情况下配对
本文关键字:情况下 反射的 gt lt 是否是 对象 何确定 种类 KeyValue 类型 | 更新日期: 2023-09-27 18:29:54
我需要确定一个对象是否属于某种类型的KeyValue对。对我来说,知道键或值使用了哪些类型并不重要。因此:`
public bool IsKeyValuePair (object o)
{
//What code should go here?
}
这个答案描述了如何使用反射来确定这一点,但在我的情况下,我正在处理成千上万的对象中的100个,这在我的应用程序中造成了瓶颈。
也许有一种方法可以用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;
}
}
}