简体   繁体   中英

How to invoke a method which returns an interface

I am invoking a method on a type via reflection which takes a couple of parameters:

var myType = typeof(myClass);

var myMethod = myType.GetMethod("myMethodInClass", 
                                 new[] { typeof(string), typeof(string) });

myMethod.Invoke(?, new object[] { "", "" });

I want the target to be an IDataReader, which is what the method will return, but I obviously cannot instantiate a new instance of an interface.

You cannot return interface, but you can return an instance of class which implement the interface your method returns. Just cast it.

IDataReader implemented = new YourClass(); // or any other constructor

Your class must only implement IDataReader interface. You can insert your class instance in the place of ? and implemented might be result of myMethod.Invoke(yourClassInstance, new object[] { "", "" }) .

myMethod.Invoke(?, new object[] { "", "" });

? has nothing with returning interface, but it's the actual object of which's method you are calling. If you know that this method returns class which implements IDataReader just write

IDataReader rd=myMethod.Invoke(yourInstance, new object[] { "", "" });.

Where you have put ? in the the question should not be IDataReader , but an instance of myClass . You are passing in the object on which you want to invoke myMethod .

The result from calling .Invoke() will be an IDataReader , but that is not something you are creating; it is created inside the method you are invoking.

你不能返回接口类型实例。但是你可以显式地转换为接口类型并且可以解决这个问题。

((myMethod.Invoke . . . ) as InterfaceType) 

Just the way you think you would:

class Gadget
{
  public IList<int> FizzBuzz( int length , int startValue )
  {
    if ( length < 0 ) throw new ArgumentOutOfRangeException("length") ;
    int[] list = new int[length];
    for ( int i = 0 ; i < list.Length ; ++i )
    {
      list[i] = startValue++ ;
    }
    return list ;
  }
}
class Program
{
  static void Main( string[] args )
  {
    object     x             = new Gadget() ;
    Type       t             = x.GetType() ;
    MethodInfo mi            = t.GetMethod("FizzBuzz") ;
    object     returnedValue = mi.Invoke( x , new object[]{ 10 , 101 } ) ;
    IList<int> returnedList  = (IList<int>) returnedValue ;
    string     msg           = returnedList.Select( n => n.ToString(CultureInfo.InvariantCulture)).Aggregate( (s,v) => string.Format("{0}...{1}" , s , v) ) ;
    Console.WriteLine(msg) ;
    return;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM