2008-09-16 27 views
3

這裏是一個我做的:如何在System.Type變量中使用「is」運算符?

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

但是,如果obj是type一個子類,它不會匹配。但是我希望函數返回的方式與我使用的運算符is相同。

我嘗試以下,但它不會編譯:

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

我想出了最好的解決辦法是:

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

是不是有使用運營商is的方式使代碼更清潔?

回答

4

當面對這個問題,我已經使用了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; 
} 

(代碼從存儲器中寫,未經測試)

2

也許

type.IsAssignableFrom(obj.GetType()) 
+0

如果我不能使用運算符'是'這將是最好的解決方案... – Jonas 2008-09-16 14:14:41

0

的是運營商表明它是否會是「安全」投下一個對象作爲另一個obeject(通常是一個超類)。

if(obj is type) 

如果obj類型的「type」或子類的它們,那麼如果語句將succeede,因爲它是「安全」投OBJ時(類型)OBJ。

看到:http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx

0

是否有一個理由,爲什麼你不能使用「的」關鍵字本身?

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()); 

     } 
    } 
    } 
+0

是的存在:C#不允許它... – 2008-09-16 13:59:14

相關問題