2012-07-26 114 views
2

我有MyClass的實例,其定義爲:的IList <T>似乎並沒有包含方法「刪除」

public partial class MyClass 
{ 
    public virtual string PropertyName1 { get; set; } 
    public virtual IList<Class2List> Class2Lists{ get; set; } 
} 

我使用反射來嘗試並找到Remove方法:

object obj1 = myClassObject; 
Type type = obj1.GetType(); 
Type typeSub = type.GetProperty("Class2Lists").PropertyType; 

//this method can not find 
MethodInfo methodRemove = typeSub.GetMethod("Remove"); 

// this method can find 
MethodInfo methodRemove = typeSub.GetMethod("RemoveAt"); 

// there is no "Remove" method in the list 
MethodInfo[] methodRemove = typeSub.GetMethods(); 

但我找不到Remove方法,爲什麼?

回答

3
  • IList<T>定義RemoveAt(),但它並沒有定義Remove()

  • IList<T>繼承自ICollection<T>,其定義爲Remove()

一個例子如何獲取正確的MethodInfo

Type typeWithRemove = typeSub.GetInterfaces() 
    .Where (i => i.GetMethod ("Remove") != null) 
    .FirstOrDefault(); 

if (typeWithRemove != null) 
{ 
    MethodInfo methodRemove = typeWithRemove.GetMethod ("Remove"); 
} 
相關問題