IList <t>似乎不包含“删除”方法</t>

时间:2012-07-26 06:22:57

标签: c# reflection

我有一个MyClass实例,定义为:

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方法,为什么?

1 个答案:

答案 0 :(得分: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" ); 
}