如何在System.Type变量中使用“is”运算符?

这是我正在做的事情:

object ReturnMatch(System.Type type) { foreach(object obj in myObjects) { if (obj == type) { return obj; } } } 

但是,如果obj是type的子type ,则它将不匹配。 但我希望函数返回的方式与我使用运算符的方式相同。

我尝试了以下,但它不会编译:

 if (obj is type) // won't compile in C# 2.0 

我想出的最佳解决方案是:

 if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type)) 

是否有使用运算符的方法is使代码更清洁?

遇到这个问题时我使用了IsAssignableFrom方法。

 Type theTypeWeWant; // From argument or whatever foreach (object o in myCollection) { if (theTypeWeWant.IsAssignableFrom(o.GetType)) return o; } 

对您的问题可能或可能不起作用的另一种方法是使用通用方法:

 private T FindObjectOfType() where T: class { foreach(object o in myCollection) { if (o is T) return (T) o; } return null; } 

(代码从内存中写入,未经过测试)

不使用is运算符,但Type.IsInstanceOfType方法似乎是您正在寻找的。

http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx

也许

 type.IsAssignableFrom(obj.GetType()) 

is运算符指示将一个对象强制转换为另一个对象(通常是超类)是否“安全”。

 if(obj is type) 

如果obj是’type’类型或其子类,则if语句将成功,因为将obj强制转换为(type)obj是“安全的”。

请参阅: http : //msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx

有没有理由不能使用“is”关键字本身?

 foreach(object obj in myObjects) { if (obj is type) { return obj; } } 

编辑 – 我看到我失踪了。 Isak的建议是正确的; 我已经测试并确认了它。

  class Level1 { } class Level2A : Level1 { } class Level2B : Level1 { } class Level3A2A : Level2A { } class Program { static void Main(string[] args) { object[] objects = new object[] {"testing", new Level1(), new Level2A(), new Level2B(), new Level3A2A(), new object() }; ReturnMatch(typeof(Level1), objects); Console.ReadLine(); } static void ReturnMatch(Type arbitraryType, object[] objects) { foreach (object obj in objects) { Type objType = obj.GetType(); Console.Write(arbitraryType.ToString() + " is "); if (!arbitraryType.IsAssignableFrom(objType)) Console.Write("not "); Console.WriteLine("assignable from " + objType.ToString()); } } }