Question

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.

Était-ce utile?

La solution 3

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.

Autres conseils

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[] { "", "" });.

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[] { "", "" }).

You cannot return interface type instance .but you can explicitly cast into interface type and can solve this out.

((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;
  }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top