2012-09-02 35 views
-1

說我有調用的組件對象的列表:如何檢查什麼類是在C#中的對象

List<object> components = new List<object>(); 

說,這是與類發動機,車輪,車架的對象填充。現在,我想創建一個將類作爲參數的函數,如果列表中有該類的對象,則返回true。像這樣:

public static bool HasComponent(*the class*) { 
    foreach(object c in components) { 
     if(c is *the class*) 
      return true; 
    } 

    return false; 
} 

我該怎麼做呢?可能嗎?

回答

3

使用generics

public static bool HasComponent<T>() { 
    foreach(object c in components) { 
     if(c is T) 
      return true; 
    } 

    return false; 
} 

叫它:

Obj.HasComponent<Wheel>(); 
+1

靜態方法。 ...來自實例的電話..... upvoters是「天才」 –

+0

大寫只爲你。 – Femaref

+0

非常感謝您的幫助 – user1494136

1

更多的東西像這樣

public static bool HasComponent<TheType>() 
{ 
    foreach(object c in components) 
    { 
     if(c is TheType) 
     { 
      return true; 
     } 
    } 
    return false; 
} 

或更短

public static bool HasComponent<TheType>() 
{ 
    return components.OfType<TheType>().Count() > 0; 
} 

HasComponent<TheType>() 
2

叫什麼你可以調用的GetType()來獲取.NET中所有對象的類型或使用is關鍵字。事實上,你可以做到這一點使用LINQ的東西,如名單上:

components.Any(x => x is Wheel); 

並替換爲Wheel所需的類型。

5

使用LINQ:

components.OfType<YouType>().Any(); 
0

要了解這一點,我們應該使用擴展的循環,是「的foreach」,它橫穿所有類型的類的對象,並檢查特定的類,並返回所預期的目的無論是真或假。

public static bool HasComponent<Type>() { 
foreach(object c in l) { 
    if(object c in Type) 
     return true; 
    } 

    return false; 
} 
0

如果您正在使用一個多線程應用程序時,你應該確保該對象是在列表中你進行搜索的時間。因爲另一個線程可以在搜索的同時刪除這個對象。所以,可能會拋出NullReferenceException。爲了避免這種情況,你可以使用這個功能。

public static bool HasComponent<T>() 
{ 
    foreach (object c in components) 
    { 
     lock (c.GetType()) 
     { 
      if (c is T) 
      { 
       return true; 
      } 
     } 

    } 
    return false; 
} 

但是,要調用這個函數,你的列表應該是靜態的。

0

我知道使用「is」關鍵字建議的一些答案,但是您會希望在繼承情況下小心。例如如果母牛來自動物,那麼HasComponent<Cow>()將返回true。你真的應該比較類型,以避免該問題:

public static bool HasComponent<T>() 
{ 
    return components.Any(i => i.GetType() == typeof(T)); 
} 

當然,你可以通過傳遞一個類型做沒有泛型,但仿製藥是真的要走的路:

public static bool HasComponent(Type type) 
{ 
    return components.Any(i => i.GetType() == type); 
}