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

时间:2020-03-05 18:55:58  来源:igfitidea点击:

这是我在做什么:

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

但是,如果obj是t​​ype的子类,则它将不匹配。但是我希望函数以与使用操作符" is"相同的方式返回。

我尝试了以下操作,但无法编译:

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

我想到的最好的解决方案是:

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

没有办法使用运算符" is"来使代码更整洁吗?

解决方案

回答

可能

type.IsAssignableFrom(obj.GetType())

回答

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

if(obj is type)

如果obj是'type'类型或者其子类,则if语句将成功,因为将obj强制转换为(type)obj是'safe'。

请参阅:http://msdn.microsoft.com/zh-cn/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());

      }
    }
  }

回答

我们没有在使用is运算符,而是使用Type.IsInstanceOfType方法。

http://msdn.microsoft.com/zh-CN/library/system.type.isinstancetanceoftype.aspx

回答

遇到此问题时,我已使用IsAssignableFrom方法。

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

可能会或者可能不会解决问题的另一种方法是使用通用方法:

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

(代码是从内存写入的,未经测试)