传入类型以进行检查 [英] Pass in Type to check against
本文介绍了传入类型以进行检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法,我在其中检查循环中的当前对象是否与我传递给方法的类型相同.
I have a method in which I'm doing a check to see if the current object in a loop is the same type as a type I pass into the method.
起初我将类型作为字符串传递给方法,然后使用:
At first I was passing the type into the method as a string and then using:
item.GetType().ToString().Equals(myType);
我真正想做的是使用 is
关键字来做:
What I'd really prefer to do is use the is
keyword to do:
item is myType
我遇到的问题是将 myType
传递给方法.我需要使用某种时髦的泛型类型吗?我将类型的引用传递为什么类型?
The problem I'm having is passing in myType
to the method. Do I need to use some kind of funky generics type or something? What type do I pass in a reference ot a type as?
推荐答案
是这样的吗?
public static bool ContainsType<T>()
{
object[] objects = new object[] { };
foreach (var o in objects)
{
if (o is T)
{
return true;
}
}
return false;
}
public static void Main(string[] args)
{
ContainsType<int>();
}
这篇关于传入类型以进行检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文