-1

假设我有一个称为组件的对象列表:

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;
} 

我该怎么做呢?是否可以?

4

7 回答 7

5

使用 linq:

components.OfType<YouType>().Any();
于 2012-09-02T13:49:10.960 回答
3

使用泛型

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

    return false;
}

称它为:

Obj.HasComponent<Wheel>();
于 2012-09-02T13:45:31.757 回答
2

您可以调用 GetType() 来获取 .Net 中任何对象的类型或使用is关键字。实际上,您可以使用 LINQ 在列表中执行此操作,例如:

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

并替换Wheel所需的类型。

于 2012-09-02T13:47:42.100 回答
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>()
于 2012-09-02T13:46:20.350 回答
0

To find this out, we should use an extended for loop that is 'foreach', which traverses through all types of class objects and checks the desired object of specific class and returns either true or false.

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

    return false;
} 
于 2012-09-02T13:52:43.000 回答
0

If you are working with a multiple-threaded application, you should be sure that the object is in the list at the time you search for it. Because the other thread can remove this object at the same time as the search. So, a NullReferenceException could be thrown. In order to avoid this situation, you can use this function.

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

     }
     return false;
}

But, to call this function your list should be static.

于 2012-09-02T14:22:07.200 回答
0

I know some answers suggested using the "is" keyword, but you'll want to be careful in inheritance situations. e.g. If Cow derives from Animal, then HasComponent<Cow>() will return true for both. You should really compare types to avoid the problem:

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

Of course, you can do it without generics by passing in a type, but generics is really the way to go:

public static bool HasComponent(Type type)
{
    return components.Any(i => i.GetType() == type);
}
于 2012-09-02T14:34:38.617 回答