簡體   English   中英

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

[英]How to use the “is” operator in System.Type variables?

這是我在做什么:

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

但是,如果obj是type的子type ,則它將不匹配。 但是我希望函數以與使用操作符is相同的方式返回。

我嘗試了以下操作,但無法編譯:

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<T>() where T: class
{
    foreach(object o in myCollection)
    {
        if (o is T)
             return (T) o;
    }
    return null;
}

(代碼是從內存寫入的,未經測試)

也許

type.IsAssignableFrom(obj.GetType())

您沒有在使用is運算符,而是使用Type.IsInstanceOfType方法。

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

is運算符指示將一個對象強制轉換為另一個對象(通常是超類)是否“安全”。

if(obj is type)

如果obj是'type'類型或其子類,則if語句將成功,因為將obj強制轉換為(type)obj是'safe'。

請參閱: 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());

      }
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM