How to call a method that returns an interface

I call the method by type through reflection, which takes several 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, and this is what the method will return, but I obviously cannot create an instance of the new interface.

+4
source share
5 answers

If you set ? , the question should not have IDataReader , but an instance of myClass . You pass the object you want to call myMethod .

The result of calling .Invoke() will be IDataReader , but this is not what you create; it is created inside the method you are calling.

+1
source

You cannot return an interface, but you can return an instance of a class that implements the interface returned by your method. Just drop it.

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

Your class should only implement the IDataReader interface. Can you insert an instance of a class instead ? , and implemented may be the result of myMethod.Invoke(yourClassInstance, new object[] { "", "" }) .

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

? has nothing with a return interface, but it is the actual object of the method that you are calling. If you know that this method returns a class that implements IDataReader , just write

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

You cannot return an instance of an interface type. But you can explicitly enter into the type of interface and solve this problem.

 ((myMethod.Invoke . . . ) as InterfaceType) 
0
source

What do you think you are:

 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; } } 
0
source

All Articles