2

次のように定義された 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方法を見つけることができません、なぜですか?

4

1 に答える 1

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" ); 
}
于 2012-07-26T06:27:05.050 に答える